8using System.Threading.Tasks;
45 : base(
"Legal/ApplyId",
46 new KeyValuePair<Type,
Expression>(typeof(Dictionary<string, object>), new
Expression(jsonPattern)),
66 string KeyId = (string)Parameters[
"PKeyId"].AssociatedObjectValue;
67 string Nonce = (string)Parameters[
"PNonce"].AssociatedObjectValue;
68 string KeySignature = (string)Parameters[
"PKeySignature"].AssociatedObjectValue;
69 string RequestSignature = (string)Parameters[
"PRequestSignature"].AssociatedObjectValue;
70 object[] PropertyNames = (
object[])Parameters[
"PPropertyName"].AssociatedObjectValue;
71 object[] PropertyValues = (
object[])Parameters[
"PPropertyValue"].AssociatedObjectValue;
72 Dictionary<CaseInsensitiveString, Property> PropertiesByName =
new Dictionary<CaseInsensitiveString, Property>();
73 List<Property> Properties =
new List<Property>();
74 StringBuilder sb =
new StringBuilder();
77 if (
string.IsNullOrEmpty(Agent))
80 if (
string.IsNullOrEmpty(KeyId))
83 if (
string.IsNullOrEmpty(Nonce) || Nonce.Length < 32)
86 if (Agent.Contains(
':') || Agent.Contains(
'/'))
88 if (!Uri.TryCreate(Agent, UriKind.Absolute, out Uri AgentUri))
102 throw new BadRequestException(
"Referer header invalid. Unable to resolve URI: " + ex.Message);
108 if (Content?.HasError ??
false)
110 if (Content.
Error is Content.Getters.WebException ex)
112 if (ex.StatusCode == HttpStatusCode.NotFound)
114 else if ((
int)ex.StatusCode >= 500)
115 throw new BadRequestException(
"Referer header invalid. Referer returns server error: " + ex.Message);
121 else if (IPAddress.TryParse(Request.
RemoteEndPoint.RemovePortNumber(), out IPAddress RemoteAddress))
125 if (RemoteAddress.AddressFamily == AddressFamily.InterNetwork)
127 else if (RemoteAddress.AddressFamily == AddressFamily.InterNetworkV6)
140 AddressRecord.
Address == RemoteAddress)
148 throw new BadRequestException(
"Referer header invalid. Domain does not match caller IP Address.");
153 throw new BadRequestException(
"Referer header invalid. Domain does not match caller domain name, as provided in certificate.");
174 sb.Append(KeySignature);
176 string s2 = sb.ToString();
180 int i, c = PropertyNames?.Length ?? 0;
181 if ((PropertyValues?.Length ?? 0) != c)
184 bool JidAdded =
false;
185 bool EMailAdded =
false;
186 bool PhoneNrAdded =
false;
188 for (i = 0; i < c; i++)
190 if (!(PropertyNames[i] is
string PropertyName) ||
string.IsNullOrEmpty(PropertyName))
193 if (!(PropertyValues[i] is
string PropertyValue) ||
string.IsNullOrEmpty(PropertyValue))
199 switch (PropertyName.ToUpper())
205 int j = PropertyValue.IndexOf(
'@');
209 if (PropertyValue[..j] != User.
UserName)
249 string s = Convert.ToBase64String(
252 Encoding.UTF8.GetBytes(s3)));
254 if (s != RequestSignature)
256 string Msg =
"Request Signature invalid.";
262 string Msg =
"Nonce value has already been used.";
274 if (!EMailAdded && !
string.IsNullOrEmpty(User.
Account.
EMail))
293 DateTime Today = DateTime.Today;
295 if (Next.Value == DateTime.MaxValue)
297 sb.Append(
"This endpoint (");
299 sb.Append(
") has been blocked from the system.");
303 sb.Append(
"Too many failed identity applications in a row registered. Try again after ");
304 sb.Append(TP.ToLongTimeString());
306 if (TP.Date != Today)
308 if (TP.Date == Today.AddDays(1))
309 sb.Append(
" tomorrow");
313 sb.Append(TP.ToShortDateString());
317 sb.Append(
". Remote Endpoint: ");
326 DateTime From = TP.Date;
335 Updated = DateTime.MinValue,
338 State = IoTBroker.Legal.Identity.IdentityState.Created,
339 Provider = LegalDomain,
340 Properties = Properties.ToArray(),
341 Version = NamespaceSet.Current
344 StringBuilder Xml =
new StringBuilder();
345 Identity.Serialize(Xml,
false,
false,
false,
false,
false,
false,
false,
null,
XmppServerModule.Legal);
346 Identity.ClientSignature = KeyEndpoint.
Sign(Encoding.UTF8.GetBytes(Xml.ToString()));
353 ToRemove.
Id.
Value, BareJid,
"LegalIdDeleted", ToRemove.GetTags());
358 Identity.Id = Identity.ObjectId +
"@" + LegalDomain;
364 KeyValuePair<string, object>[] Tags = Identity.GetTags();
366 Log.
Informational(
"Legal Identity application registered.", Identity.Id.Value, BareJid,
367 "LegalIdRegistered", Tags);
369 XmppServerModule.Legal?.IdentityAuthorization(BareJid, BareJid, Identity.Id,
true);
372 Identity.Serialize(Xml,
true,
true,
true,
true,
true,
true,
true,
null,
XmppServerModule.Legal);
373 string IdentityXml = Xml.ToString();
375 XmlDocument IdentityDoc =
XML.
ParseXml(IdentityXml,
true);
379 {
"Identity", IdentityDoc }
384 StringBuilder Markdown =
new StringBuilder();
386 Markdown.Append(
"Legal identity application received: [`");
387 Markdown.Append(Identity.Id);
388 Markdown.Append(
"`](");
390 Markdown.Append(Identity.Id);
391 Markdown.AppendLine(
")");
392 Markdown.AppendLine();
407 case IoTBroker.Legal.Identity.IdentityState.Created:
408 case IoTBroker.Legal.Identity.IdentityState.Approved:
413 Markdown.AppendLine(
"Other identities registered for the same account:");
420 Markdown.Append(
"[`");
421 Markdown.Append(ID.
Id);
422 Markdown.Append(
"`](");
424 Markdown.Append(ID.
Id);
425 Markdown.AppendLine(
")");
426 Markdown.AppendLine();
440 string.Empty, IdentityXml);
453 string s4 = s2 +
":" + Convert.ToBase64String(
AgentKey.
Salt);
455 byte[] IV =
new byte[16];
459 Aes Aes = Aes.Create();
463 Aes.Mode = CipherMode.CBC;
464 Aes.Padding = PaddingMode.PKCS7;
466 using ICryptoTransform Decryptor = Aes.CreateDecryptor(Key, IV);
473 Doc =
XML.
ParseXml(Encoding.UTF8.GetString(Decrypted));
Contains information about a response to a content request.
Exception Error
Error response.
Static class managing encoding and decoding of internet content.
static Task< ContentResponse > GetAsync(Uri Uri, params KeyValuePair< string, string >[] Headers)
Gets a resource, given its URI.
A Named dictionary is a dictionary, with a local name and a namespace. Use it to return content that ...
Helps with common XML-related tasks.
static XmlDocument ParseXml(string Xml)
Parses an XML Document from its string representation.
Static class managing the application event log. Applications and services log events on this static ...
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Static class managing the runtime environment of the IoT Gateway.
static CaseInsensitiveString Domain
Domain name.
static bool IsDomain(string DomainOrHost, bool IncludeAlternativeDomains)
If a domain or host name represents the gateway.
static Task< bool > HasNonceBeenUsed(string Nonce)
Checks if a Nonce value has been used.
static LoginAuditor LoginAuditor
Current Login Auditor. Should be used by modules accepting user logins, to protect the system from un...
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
static string GetUrl(string LocalResource)
Gets a URL for a resource.
static Task RegisterNonceValue(string Nonce)
Registers a nonce value.
static bool HasDomain
If a domain name is configured.
DNS resolver, as defined in:
static Task< ResourceRecord[]> TryResolve(string Name, QTYPE TYPE, QCLASS CLASS)
Tries to resolve a DNS name.
Abstract base class for Resource Address Records.
IPAddress Address
IP address
Abstract base class for a resource record.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
The server understood the request, but is refusing to fulfill it. Authorization will not help and the...
Represents an HTTP request.
HttpRequestHeader Header
Request header.
string RemoteEndPoint
Remote end-point.
Represets a response of an HTTP client request.
The server has not found anything matching the Request-URI. No indication is given of whether the con...
The server is currently unable to handle the request due to a temporary overloading or maintenance of...
The user has sent too many requests in a given amount of time. Intended for use with rate limiting sc...
IE2eEndpoint Parse(XmlElement Xml)
Parses endpoint information from an XML element.
abstract string LocalName
Local name of the E2E encryption scheme
Abstract base class for Elliptic Curve endpoints.
override byte[] PublicKey
Remote public key.
override byte[] Sign(byte[] Data)
Signs binary data using the local private key.
XmppAddress MainDomain
Main/principal domain address
Contains information about one XMPP address.
CaseInsensitiveString Address
XMPP Address
Task< bool > SendMessage(string Type, string Id, string From, string To, string Language, string ContentXml)
Sends a Message stanza to a recipient.
bool IsServerDomain(CaseInsensitiveString Domain, bool IncludeAlternativeDomains)
Checks if a domain is the server domain, or optionally, an alternative domain.
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
static bool IsNullOrEmpty(CaseInsensitiveString value)
Indicates whether the specified string is null or an CaseInsensitiveString.Empty string.
Static interface for database persistence. In order to work, a database provider has to be assigned t...
static Task< IEnumerable< object > > FindDelete(string Collection, params string[] SortOrder)
Finds objects in a given collection and deletes them in the same atomic operation.
static async Task Update(object Object)
Updates an object in the database.
static Task< IEnumerable< object > > Find(string Collection, params string[] SortOrder)
Finds objects in a given collection.
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
This filter selects objects that conform to all child-filters provided.
This filter selects objects that have a named field equal to a given value.
This filter selects objects that have a named field not equal to a given value.
Static class managing persistent counters.
static Task< long > IncrementCounter(CaseInsensitiveString Key)
Increments a counter.
Static class managing loading of resources stored as embedded resources or in content files.
static string LoadResourceAsText(string ResourceName)
Loads a text resource from an embedded resource.
Static class managing persistent settings.
static async Task< string > GetAsync(string Key, string DefaultValue)
Gets a string-valued setting.
Class managing a script expression.
Contains methods for simple hash calculations.
static byte[] ComputeHMACSHA256Hash(byte[] Key, byte[] Data)
Computes the HMAC-SHA-256 hash of a block of binary data.
static byte[] ComputeSHA256Hash(byte[] Data)
Computes the SHA-256 hash of a block of binary data.
Contains information about a broker account.
CaseInsensitiveString EMail
E-mail address associated with account.
string Password
Password of account
CaseInsensitiveString PhoneNr
Phone number associated with account.
Account Account
Account object.
string UserName
User Name.
CaseInsensitiveString Id
ID of the legal identity
IdentityState State
Current state of identity
override string ToString()
Object.ToString()
CaseInsensitiveString Name
Property name
CaseInsensitiveString Value
Property value
Legal (digital identities, smart contracts) service component.
static DateTime UtcNowSecond
Current Date & Time (in UTC), to a precision of one second.
Provides the user with options to control notifications from the Broker.
static BrokerNotificationConfiguration Instance
Current instance of configuration.
bool OtherLegalIds
If a notification should be sent for every existing valid Legal ID that exists when a new Legal ID ap...
bool LegalIdReceived
If a notification should be sent when a new a Legal ID application is received.
Abstract base class for agent resources supporting the POST method.
static AccountUser AssertUserAuthenticated(HttpRequest Request)
Makes sure the request is made by an authenticated API user.
const string AgentNamespace
https://waher.se/Schema/BrokerAgent.xsd
Contains an encrypted key for an agent.
byte[] Salt
Cryptographic salt.
string Namespace
Namespace of algorithm
string LocalName
Local Name of algorithm
byte[] EncryptedKey
Encypted key.
Gets available cryptographic algorithms.
static bool TryGetAlgorithm(string LocalName, string Namespace, out EllipticCurveEndpoint Algorithm)
Tries to get an algorithm given its fully qualified name.
Applies for a new Legal ID
ApplyId()
Applies for a new Legal ID
override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary< string, IElement > Parameters)
Executes the POST method on the resource.
Service Module hosting the XMPP broker and its components.
QTYPE
QTYPE fields appear in the question part of a query.
QCLASS
QCLASS fields appear in the question section of a query.