mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
7dc514b52f2c96bdd1ea32ae64a02703f85be2aa
25
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e3e06a1122 |
feat(iot): add RegisterCertificateWithoutCA and the V2 principal lists (#5772)
* feat(iot): add RegisterCertificateWithoutCA and the V2 principal lists RegisterCertificateWithoutCA registers a certificate from any issuer in SNI_ONLY mode. ListThingPrincipalsV2 and ListPrincipalThingsV2 page the thing principal attachments and report each one as NON_EXCLUSIVE_THING, because Floci does not model exclusive attachment. * fix(iot): validate the principal and page size of the V2 principal lists ListPrincipalThingsV2 requires a principal, and both V2 lists accept 1 to 250 results per page, as on AWS. Tests cover these checks and the RegisterCertificateWithoutCA rejection of a missing PEM and an unknown status. * fix(iot): refuse a device certificate registered in more than one account AWS selects the account from the server name, which Floci does not do yet. The MQTT TLS listener therefore refuses a certificate that more than one account registers, instead of admitting it under the lowest account ID. RegisterCertificateWithoutCA drops the cached location, and the lookup runs under compute, so a connect cannot cache a stale account. * fix(iot): make the RegisterCertificateWithoutCA duplicate check atomic A lock holds the duplicate check and the store write together, as CreateAuthorizer does, so two identical registrations at the same moment store one certificate and the other caller gets the 409. The 409 carries resourceId and resourceArn, as AWS lists for this call. |
||
|
|
534571b2a3 |
feat(iot): route shadow events through topic rules (#5260)
* feat(iot): route shadow events through topic rules Successful classic and named shadow changes, from the REST API and from MQTT reserved topics, now reach the topic rules engine and MQTT subscribers on the AWS response topics with AWS payload shapes. Shadow documents keep metadata, clientid() reports N/A for messages without an MQTT client, and MQTT rejected responses carry the numeric status code. Closes floci-io/floci#5256 * fix(iot): compute the shadow delta through nested objects GetThingShadow and the update/delta event compared desired and reported only at the top level, so one differing nested field put the whole desired object in the delta. AWS compares nested objects key by key and arrays whole, and the delta event carries the stored desired metadata of exactly the delta values. * fix(iot): give a shadow stored without metadata its leaf metadata A shadow persisted before metadata was kept now reads back with a metadata mirror of its state stamped with its stored timestamp, so GetThingShadow and the update/documents and update/delta events carry metadata for its existing leaves, as AWS does for every state leaf. * fix(iot): reject a shadow name outside the AWS pattern A whitespace-only shadow name no longer addresses the classic shadow, so DELETE ?name=%20 cannot delete it. As on AWS, an empty name is the classic shadow and any name that is not 1 to 64 of [a-zA-Z0-9:_-] fails with InvalidRequestException. * fix(iot): ignore a shadow request on a named topic with an invalid name As on AWS, an MQTT request on $aws/things/<thing>/shadow/name/<name>/<op> whose name is not a valid shadow name, empty included, is not a shadow request: nothing is published and the classic shadow is untouched. Before, an empty name updated the classic shadow and a blank one was rejected on the classic shadow's topic. * docs(iot): note that wildcard rule filters receive shadow events Verified on AWS IoT: rules FROM '#' and '+/things/<thing>/shadow/#' receive the $aws shadow update events. Adds a test locking in the existing matcher behavior. * fix(iot): keep only the most recent recorded publish events The recorder kept every publish, and shadow events now go through it too. Only tests read it, so it now keeps the most recent 1,000 events and drops the oldest. * test(iot): read shadow rule queues without the 5s poll * fix(iot): match AWS shadow names, delta numbers and clientToken echo Accept the reserved $package shadow name and reject any other name containing $ with 'Invalid shadow name : <name>'; a name failing the pattern answers 'Bad Request'. Compare delta numbers as AWS does (equal when both double and long values are, integers beyond long exactly), which also stops a number beyond the double range failing the update, and echo a whitespace clientToken. |
||
|
|
caa606ba7d |
fix(iot): resolve connect policy variables through the IAM resolver (#5827)
IoT carried its own policy-variable pass. Before handing the attached documents
to the evaluator, IotService walked each statement's parsed tree, replaced the
connection's ${iot:...} values in every string it found, and dropped any
statement that still held a ${...}. That was IoT's copy of the mechanism the
evaluator gained for every other policy Floci reads, so the documents now go in
as written and PolicyVariableResolver does the substituting, from the same
condition context the connection already supplies.
The developer guide gives IoT no policy language of its own to justify a second
reader: AWS IoT Core policies "are JSON documents. They follow the same
conventions as IAM policies", they "follow the same policy evaluation logic as
IAM policies", and a policy variable is one "that can be used in AWS IoT Core
policies in the Resource or Condition block". The predefined ${*}, ${?} and
${$} are documented by pointing at IAM's own variables page.
Five corners move, each of them onto what those pages say:
- A ${...} outside Resource and Condition is text. The text pass substituted
into every string of the statement, Action and Sid included, where the guide
gives a variable meaning in those two elements only.
- ${*}, ${?} and ${$} resolve to the characters they stand for. Any statement
holding one used to be dropped, the unresolved-variable scan being a plain
\$\{[^}]*\} that matched them too.
- A variable resolves whatever case its key is written in, the variables page
being explicit that "Key names are case-insensitive. For example,
aws:CurrentTime is equivalent to AWS:currenttime". A thing attribute spelled
two ways in one registry now collides on that reading, which is the price of
the IAM rule and not a surprise unique to IoT.
- An unresolvable variable in a Condition value leaves the value null rather
than taking the whole statement away, so a positive operator does not match
and a negated one does. A Resource pattern holding one still matches no
resource, which is what dropping the statement amounted to.
- Variables need the version that introduced them. A document that does not
declare "Version": "2012-10-17" keeps ${iot:ClientId} as literal text, the
guide's answer being that "if you don't set the Version to 2012-10-17 or
later, variables like ${aws:username} are treated as literal strings in the
policy". Every policy example in the IoT guide declares it.
A connection no longer rewrites the document it evaluates, which the evaluator's
parse cache notices: it is keyed by document text, so it held one entry per
client id where it now holds one per policy.
Five tests in IotServiceDeviceAuthTest cover the five corners, and the
unresolved-variable, JSON-syntax and thing-attribute tests already there cover
what has to stay put. docs/services/iot.md says what resolves where.
|
||
|
|
1082941bc2 |
feat(iot): search the supported fleet index subset (#4913)
Floci served the fleet indexing configuration but not SearchIndex, so an application that finds its things by name, type, group or attribute got "Unknown operation: POST /indices/search". SearchIndex now runs on POST /indices/search over the things of the caller's account and region, in thing name order. Its page token names the last thing returned, so a page continues after it even when things before it were deleted, as measured on AWS. Like AWS's, a token continues only the request that issued it: another queryString, or an indexName or queryVersion sent differently, is "nextToken was from a request with different parameters", and an empty, forged, edited or truncated token is "Invalid nextToken". A new parser, IotFleetIndexQuery, evaluates field:value terms with case-insensitive values, case-sensitive field names, * and ? wildcards, existence and match-all, quoted values, AND, OR and NOT with their symbolic forms, leading - negation and parentheses. Precedence is the one measured on AWS, where whitespace is an AND that binds looser than OR. The fields are thingName, thingId, thingTypeName, thingGroupNames and attributes.*. Requests are validated with the messages and in the order measured on AWS: a body that is not a JSON object and every member type, member constraints, index name, query version, a disabled index, the query, then the page token. Within the query a syntax error comes first, then the 12-term limit, in which each value of a field group counts and the field does not, then the first other error, where the field of a group is checked like any other field. A range counts as one term, and a malformed range or an unescaped bracket outside one is a syntax error. AWS's limits hold: a queryString of at most 1000 characters, at most 12 terms, at most two * wildcards in a value and no value starting with ?. maxResults takes any number, truncated toward zero and capped at the int range as on AWS. A classic shadow field needs REGISTRY_AND_SHADOW indexing, and a named shadow field named shadow indexing and a shadow in its filter, or it is AWS's invalid field name. Constructs AWS accepts but Floci does not evaluate, such as ranges, comparisons, free text, field grouping and shadow or Device Defender fields, are refused with InvalidQueryException instead of matching nothing, and so is a search of AWS_ThingGroups. Connectivity fields are refused like shadow and Device Defender fields: AWS's InvalidRequestException while connectivity indexing is off, InvalidQueryException once it is on. Documents leave out the members a thing lacks and never carry a shadow or a connectivity member, where AWS adds connectivity while connectivity indexing is on. |
||
|
|
f413a667d0 |
feat(iot): indexing configuration (#4896)
AWS IoT fleet indexing had no routes in Floci, so a stack or script
calling UpdateIndexingConfiguration or GetIndexingConfiguration failed
with "Unknown operation: POST /indexing/config", and there was no
stored configuration for a later SearchIndex to consult.
A new IotFleetIndexingService and IotFleetIndexingController, wired
into the iot descriptor beside the domain configuration controller,
serve UpdateIndexingConfiguration and GetIndexingConfiguration on
/indexing/config and DescribeIndex on /indices/{indexName}. There is
one configuration per account and region, kept through StorageFactory;
a region never updated reports the OFF shape AWS returns.
The behaviour follows what real AWS returned when measured: an update
that carries only one of the thing and thing group configurations
keeps the other, turning thing indexing OFF clears the whole thing
configuration, and managedFields are derived from the modes rather
than stored. Client sent managedFields are only checked against the
fields AWS manages and their types. Validation uses AWS's messages for
a missing configuration, null and out of set enum values (the modes,
field types, filter socket information and geolocation order),
secondary modes without thing indexing, named shadow indexing without
shadow names, unknown managed fields, and a thing custom field named
after a managed field. A geolocation sent without an order is stored
with LatLon, the default AWS returns. DescribeIndex returns the
schema the modes select and is ACTIVE at once, a disabled index is
ResourceNotFoundException and an unknown name InvalidRequestException.
Thing group managedFields are checked the same way, also while group
indexing is OFF, and neither group managedFields nor customFields are
stored. A member of the wrong JSON type is a SerializationException,
as on AWS. The fleet indexing, domain configuration and authorizer
controllers now share one strict body reader, so a malformed body or
content after it is a SerializationException on all three, which is
what AWS returns there.
ListIndices, SearchIndex and the statistics APIs are not modeled.
|
||
|
|
a33eea05cd |
feat(iot): enforce custom authorizer decisions on MQTT connections (#4835)
* test(iot): cover custom authorizer invocation and enforcement against AWS * feat(iot): enforce custom authorizer decisions on MQTT connections Serve TestInvokeAuthorizer and invoke an authorizer's function on an MQTT CONNECT that names it, on the plaintext listener and the /mqtt WebSocket bridge. The event, the request and answer checks, signed-token verification and the refusal per MQTT version follow what was measured against AWS IoT Core. The bridge hands the upgrade's headers, query and server name to the broker keyed by its connection's local address. Closes #4823 * fix(iot): evaluate WebSocket custom authorizer policies against the client's address * docs(iot): note that a non-UTF-8 MQTT password reaches the authorizer altered * test(iot): cover custom authorizer CONNECTs on the plain MQTT listener * fix(iot): refuse TestInvokeAuthorizer tokens and signatures outside their length bounds * fix(iot): refuse authorizer JSON with trailing content TestInvokeAuthorizer, CreateAuthorizer and UpdateAuthorizer bodies, a custom authorizer's answer and each policy document it returns are now read with FAIL_ON_TRAILING_TOKENS, as the shared JSON controllers do, so a valid prefix followed by junk is refused instead of half-read. * fix(iot): keep address literals out of the WebSocket server name Over WSS without SNI the bridge fell back to the Host header unfiltered, so a client dialing an IP got that IP as tls.serverName in the authorizer event and as iot:DomainName in policy evaluation. Apply the same address literal filter SNI already uses. Also name the context validation ceiling in TestInvokeAuthorizer's ponytail note. |
||
|
|
4be8309e8d |
feat(cloudformation): provision AWS::IoT::Authorizer (#4830)
* test(cloudformation): cover AWS::IoT::Authorizer against AWS * feat(cloudformation): provision AWS::IoT::Authorizer CloudFormation stubbed AWS::IoT::Authorizer with a fake ARN and created nothing. IotAuthorizerCfnProvisioner now creates a real authorizer through IotAuthorizerService. Ref is the authorizer name and Fn::GetAtt Arn the ARN. A missing AuthorizerFunctionArn fails with the registry's model validation error before any call. Status, EnableCachingForHttp, AuthorizerFunctionArn and the token settings update in place, sending only the declared properties, tags are reconciled, and a failed stack update restores them from a snapshot. Changing AuthorizerName or SigningDisabled replaces the authorizer and deletes the old one once the update commits; a replacement that keeps an explicit name is refused. Delete deactivates the authorizer first and tolerates one already gone. Closes #4822 * chore(cloudformation): move the IoT authorizer snapshot constant It sat at the same insertion point as other pull requests' snapshot constants, so they could not be merged together. * fix(cloudformation): treat only an empty intrinsic result as AWS::NoValue for IoT authorizers * fix(cloudformation): undo an IoT authorizer update whose tag reconcile fails * fix(cloudformation): report a SigningDisabled change on an IoT authorizer as a replacement * fix(cloudformation): create an IoT authorizer over a dispatcher stub and refuse declaring its generated name * fix(cloudformation): refuse an IoT authorizer boolean that is neither true nor false * fix(cloudformation): never delete a dispatcher stub's id in replacement cleanup * fix(cloudformation): tell a stub from a migrated resource and roll back a stub migration that kept its id * fix(cloudformation): name an unnamed IoT authorizer <LogicalId>_<12 chars> as CloudFormation does |
||
|
|
fabcd6baf8 |
feat(iot): manage custom authorizers (#4826)
* test(iot): cover custom authorizer management against AWS * feat(iot): manage custom authorizers Serve CreateAuthorizer, DescribeAuthorizer, UpdateAuthorizer, DeleteAuthorizer, ListAuthorizers, SetDefaultAuthorizer, DescribeDefaultAuthorizer and ClearDefaultAuthorizer on the AWS REST-JSON paths, with the validation, messages, defaults, key merge, delete rules, ordering and paging measured against AWS. Authorizer ARNs are tagged through the existing IoT tag routes. Authorizers are stored, not evaluated. Closes #4821 * fix(iot): read authorizer public key PEM line by line like AWS A key without its PEM header line, or with an indented or inline header, is not a valid RSA key, a header without its end line cannot convert, and text before the header is skipped, as measured on AWS. * fix(iot): validate authorizer names like AWS, SetDefaultAuthorizer included A name member reports every violated constraint in one message, the pattern first, and a missing one must not be null. SetDefaultAuthorizer validates authorizerName before the lookup, as measured on AWS. * fix(iot): validate the authorizer name on describe, update and delete like AWS DescribeAuthorizer, UpdateAuthorizer and DeleteAuthorizer now reject a malformed or overlong authorizerName path member with AWS's 400 InvalidRequestException messages instead of a 404, measured on eu-west-1. * fix(iot): route tag calls to the authorizer service on the ARN resource IotTagHandler matched ":authorizer/" anywhere in the ARN, so an ARN with that text outside the resource field reached the authorizer service and failed with a 500. It now routes on the parsed resource prefix, and any other IoT ARN goes through IotService as before. |
||
|
|
84363f9570 |
fix(iot): run MQTT topic rules off the event loop (#4462)
An MQTT publish ran every matching topic rule action on the Vert.x event loop serving the connection before fanning the message out, so a slow action stalled every client on that loop and delayed delivery to subscribers. The broker now stores the retained message, records the publish, sends the PUBACK and fans out on the event loop, and hands topic rule evaluation to a single-thread worker executor of its own. IoT Data Publish still evaluates its rules before it returns. At most 1,000 evaluations are pending; beyond that a publish is still delivered but its rules are skipped, with one warning until the backlog drains. A state reset or a broker shutdown skips the rules still waiting, and an MQTT publish received during the reset or while the broker is stopped runs none. |
||
|
|
f51679c1f6 |
fix(iot): parse exponent and large integer literals in rule SQL (#4441)
A number literal written with an exponent (1e5, 1E-3) or an integer beyond 64 bits failed to parse, so in the default lenient mode the rule fell back to a passthrough that ignored WHERE, and in strict mode CreateTopicRule was rejected. The tokenizer now reads an optional exponent and such literals become decimals, following the JSON number syntax AWS IoT SQL uses for literals. |
||
|
|
5bad6774f6 |
refactor(dynamodb): isolate backend operation execution (#4379)
* refactor(dynamodb): route wire operations through a backend seam Rename the native wire handlers to NativeDynamoDbJsonHandler and NativeDynamoDbStreamsJsonHandler. Add DynamoDbOperations as the raw operation seam, plus typed DynamoDbItemAccess and DynamoDbTableAccess contracts. Add NativeDynamoDbBackend behind the seam and DynamoDbBackendSelector as the one immutable selection. Keep DynamoDbJsonHandler and DynamoDbStreamsJsonHandler as thin entry points that resolve account and region. Add RequestScopes.callAsChecked and let AslExecutor delegate to it. * refactor(dynamodb): route Java consumers through DynamoDbFacade DynamoDbFacade hands out the selected item and table capabilities and is now the one DynamoDB Resource Explorer provider in place of DynamoDbService. CloudFormation, Step Functions, the IAM condition context and the Redshift backfill call it with an explicit scope; the IoT dynamoDBv2 action writes as the rule's owning account. |
||
|
|
ec40bcf5f4 |
fix(iot): accept MQTT packets up to the AWS 128 KB payload limit (#4307)
* test(iot): 128 KB MQTT payloads on every transport, failing * fix(iot): accept MQTT packets up to the AWS 128 KB payload limit * test(iot): pin the 146 KB MQTT 5 packet limit with AWS maximum properties |
||
|
|
c4027bbf54 |
feat(iot): MQTT over WebSocket at /mqtt (#3150)
* test(iot): MQTT over WebSocket at /mqtt, failing * feat(http): echo MQTT WebSocket subprotocols * feat(iot): MQTT over WebSocket at /mqtt Bridges a WebSocket upgrade on /mqtt (HTTP and HTTPS) onto the broker's plaintext listener, so wss://host:443/mqtt works on the 443:4566 mapping with the same certificate as HTTPS and no extra listener or config. * docs(iot): MQTT over WebSocket at /mqtt * feat(iot): do not queue the /mqtt handshake behind ordered blocking tasks * fix(iot): forward only binary WebSocket frames to the broker One frame handler decides per frame: text closes with 1003, binary and continuation frames are written to the broker socket, control frames are left to Vert.x. Nothing else reads the frames, so a text payload can never reach the MQTT stream. * test(iot): AWS contract and framing tests for MQTT over WebSocket Handshake: only GET upgrades (405), unsupported version is 426, each MQTT subprotocol name is echoed and the first supported offer wins, ping gets pong, non-upgrade requests fall through. Framing (MQTT 3.1.1 section 6): a CONNECT split across two frames, two packets in one frame, garbage bytes and a frame over the transport limit. Session semantics as on AWS: MQTT 5 over wss, client id takeover across transports, retained messages, QoS 2 disconnects, shadow topics, topic rules, keep-alive pings and the IoT Data connection APIs on a WebSocket session. * test(iot): log the tolerated exceptions in the WebSocket contract tests * test(iot): pin the MQTT TLS port and the unrelated-subprotocol handshake The profile pins floci.services.iot.mqtt.tls-port now that #3142 opens 8883 whenever TLS is on. A client offering only graphql-ws on an API Gateway WebSocket path still connects, with no subprotocol echoed: the server-wide MQTT list does not affect other WebSocket routes. * test(iot): pin the deployment claims of MQTT over WebSocket Every claim the docs and comments make now has a test that fails without the behaviour: ws and wss share one port through TlsProxyServer (the 443:4566 path), a hostname learned by ensureHost serves /mqtt to a client verifying that name, the first upgrade starts a lazy broker (also eight at once, and again after a stop), a text frame or an abrupt TCP drop after a live CONNECT frees the broker session, 30 connect and disconnect cycles leave nothing behind, and the burst is 1000 messages. * test(iot): force-close the Paho client the broker stop left behind * test(iot): wait for the dropped session before closing the Paho client |
||
|
|
b88034cd1d |
feat(iot): rule SQL message functions, isNull, isUndefined, IN and array literals (#3036)
Add clientid(), timestamp(), accountid() and newuuid(), the isNull() and isUndefined() functions, the IN operator against a payload array or an array literal, and array literals such as [lat, long], each following the tables in the AWS IoT SQL reference. Equality extends to arrays (element by element, in order) and objects (by key, in any order). clientid() needs the MQTT client that published, so publish and handlePublish carry the client id: the broker passes its session's client id and an IoT Data Publish over HTTP passes none, which the function reports as n/a as AWS does. principal() stays unparsed: it returns the certificate a device authenticated with, and the broker does not verify one yet. |
||
|
|
53a84c8890 |
feat(iot): configurable DescribeEndpoint address for published AWS IoT ports (#3202)
* feat(iot): configurable DescribeEndpoint address for published AWS IoT ports AWS IoT's DescribeEndpoint returns a bare hostname and each client adds its own port (8883, 443 or 8443). Floci returns host:4566 because its HTTP data plane lives there and IoT Data clients build https://<endpoint> from it. Both are right for their callers, and Floci inside a container cannot tell whether the operator published the AWS ports. floci.services.iot.endpoint-address (FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS) is returned as is for every endpoint type when set; unset or blank keeps the host and port of the base URL. EmulatorConfig.iotEndpointAddress() resolves it once for DescribeEndpoint and for the AWS-managed domain configurations, which now follow a changed address instead of keeping the value they were seeded with. The name joins the generated server certificate's SANs the way FLOCI_HOSTNAME does, so devices verify it on 8883 and 443. * docs(iot): DescribeEndpoint address when the AWS IoT ports are published Describe FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS on the IoT page with the compose port layout it is meant for, note it on the TLS page next to the other names the server certificate covers, and list the IoT Core variables in the environment variable reference. * fix(tls): accept only host or host:port as the IoT endpoint certificate name A value with a query or fragment, such as host?x=1, still parsed to a host and was added to the server certificate. The name now has to be exactly the authority java.net.URI reads back, so anything beyond host[:port] is skipped with the same warning as a URL or a path. * test(iot): pin the address the concurrent seeding test asserts at the end Every caller had already been joined, so the final describe could not race, but setting the address explicitly before it makes that plain to read. |
||
|
|
19a85360e1 |
feat(iot): verify device certificates on the MQTT TLS listener (#3180)
* feat(iot): registered-certificate lookup and iot:Connect evaluation * feat(iot): verify device certificates and iot:Connect on the MQTT TLS listener * docs(iot): device verification on the MQTT TLS listener * test(iot): device evaluation over plain stores and under racing policy and thing changes * fix(iot): remember where a device certificate was found and log refusals at debug * fix(iot): treat any address literal in SNI as no domain name |
||
|
|
ee2f55b784 |
feat(iot): MQTT over TLS listener on 8883 (#3142)
* feat(iot): floci.services.iot.mqtt.tls-port (default 8883) * feat(iot): key manager that follows the TLS registry's current default certificate * feat(iot): MQTT over TLS listener on 8883 Second MqttServer sharing the plaintext handlers, opened when floci.tls.enabled is true. Its key material is the TLS registry's default configuration through a reloading key manager, so a server certificate reissued for a learned hostname is presented on the next handshake without rebuilding the listener. Client certificates are requested and carried through the handshake, not yet verified. * docs(iot): MQTT over TLS on 8883 * feat(iot): keep retired server key material readable for the life of a handshake A retired generation of ReloadingKeyManager stays readable for 60 seconds after its replacement, longer than Vert.x's 10 second handshake timeout, and is dropped on the next reload after that. Any number of reloads between JSSE choosing an alias and reading its key and chain now resolve to matching material. * fix(iot): wait for a failed MQTT listener to close before reporting the start failure |
||
|
|
d45c64545d |
feat(iot): evaluate the SQL subset of topic rules (#3021)
* feat(iot): evaluate the SQL subset of topic rules Topic rules only extracted the FROM topic filter and sent the whole payload to every action. The SELECT list and the WHERE clause were ignored, so a rule fired on every matching topic and its actions never received the projected document. Add a small hand written parser and evaluator under services/iot/rules for the SELECT/FROM/WHERE subset AWS rules use most: '*', dotted field paths, topic() and topic(n) with optional AS aliases, and a WHERE of startswith, endswith, comparison operators, AND, OR, NOT and parentheses. A missing field or a mismatched type is Undefined as in AWS, so an undefined predicate never fires the rule. A statement outside the subset is not rejected. It is stored as sent and keeps its previous behaviour, firing on every matching topic with the whole payload, and logs one WARN naming the token that could not be parsed. floci.services.iot.rule-sql-strict, off by default, rejects it with SqlParseException the way AWS does. Each rule is parsed once: the result is held on the rule object as a transient field that is never persisted and is rebuilt on the first publish after a restart. * fix(iot): count real tokens in the rule SQL limit and compare numbers exactly The token limit counted the end marker, so a statement with exactly 1000 tokens was rejected and the error named the end of input. Mixing a whole number with a decimal literal went through double, so 9007199254740993 compared equal to 9007199254740992.0. * fix(iot): keep rule SQL decimal literals exact Double.parseDouble rounded a decimal literal before evaluation, so level = 9007199254740993.0 matched a payload holding 9007199254740992. * fix(iot): treat a rule SQL number too large for a double as Undefined Comparing an infinity, which Jackson produces for a JSON number wider than a double, converted both operands to the same infinity and made distinct values compare equal. * fix(iot): follow the AWS IoT SQL operator tables and harden the rule parser The comparison and logic semantics did not match the operator tables in the AWS IoT SQL reference: = and <> on mismatched types are false and true rather than Undefined, JSON null is a value that equals only NULL, the ordering operators convert numeric strings, AND, OR and NOT accept the strings "true" and "false" and give Undefined for anything else instead of three valued logic, and startswith and endswith convert non-string arguments. String literals may use double quotes, as AWS's own examples do, and an unsupported function is named before its arguments are parsed so the WARN reports the function rather than a token inside it. Add a corpus of AWS reference statements sorted into parsed and unparsed, a deterministic mutation fuzz that requires the parser to raise nothing but RuleSqlParseException and the evaluator nothing at all, and tables for keyword prefixed field names, spacing, associativity, unicode and literal forms. * fix(iot): treat a rule SQL numeric string with an overflowing exponent as Undefined A payload string such as "1e-2147483648" matches the numeric string form but BigDecimal cannot hold its exponent, and the NumberFormatException escaped the publish path. It now evaluates as Undefined, and the fuzz payloads carry such strings. * docs(iot): name the AWS null functions, not IS NULL, in the rule SQL limitations * fix(iot): read rule SQL payload numbers exactly instead of through a double Jackson read payload floats as doubles, so 9007199254740993.0 arrived as 9007199254740992, 1e-400 as 0 and 0.30000000000000004 as 0.3 before the evaluator compared them against an exact literal, and a predicate could fire or stay silent for the wrong reason. The representability guard only caught the infinity case of that loss. Payload numbers are now read as BigDecimal, kept as written, so every comparison is exact at any size or precision as AWS's Decimal is, a projected number keeps its text, and the infinity handling is gone because no double is ever produced. * docs(iot): awsIotSqlVersion is stored and echoed, only its array semantics are not modelled |
||
|
|
c67e598594 |
feat(iot): real device certificates issued by the local CA (#3079)
* feat(iot): CreateKeysAndCertificate issues a real client certificate from the local CA certificateId is sha256(DER) in lowercase hex as on AWS; the returned RSA 2048 key pair matches the certificate. CreateCertificateFromCsr parses the PKCS#10, checks its self-signature and key strength (RSA 2048 or more, EC P-256/384/521), signs the CSR's key with the same CA and returns no private key, as on AWS. * docs(iot): describe the CA-issued device certificates * fix(iot): accept only the NIST curves AWS IoT names and never store a device private key The CSR key check reads the named-curve identifier instead of the field size, so secp256k1 and explicit curve parameters are refused as on AWS. The stored certificate record no longer carries the private key; it is returned once. * feat(iot): device certificates expire at the end of 2049 and DescribeCertificate reports validity AWS IoT-issued client certificates all carry notAfter 2049-12-31T23:59:59Z. CertificateGenerator gains an overload with an explicit validity window; DescribeCertificate adds validity.notBefore, validity.notAfter and certificateMode DEFAULT. The Java SDK compatibility test asserts the shape. * fix(iot): a device certificate never outlives its issuing CA A new local CA is valid until the end of 2050, past AWS's fixed 2049 device expiry; a CA created earlier (ten years) caps the device certificates it signs at its own expiry, so a chain never expires before its leaf. * fix(iot): derive CA and device expiry from creation time, never mint an expired certificate A CA created after 2050 lives ten years from creation instead of ending on the fixed date; after 2049 a device certificate lives a year, still capped at its CA. The Python compatibility suite now sends a real PKCS#10 request, since the placeholder it used is refused as on AWS. * docs(tls): the local CA now signs IoT device certificates * test(iot): pass the certificate authority to IotServiceTest's constructor |
||
|
|
67bbd2cf13 |
feat: serve custom domains over TLS as soon as they are created (#3086)
* feat(tls): record runtime-learned hostnames in the certificate metadata
* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime
Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.
* feat(tls): keep runtime-learned hostnames across a boot regeneration
* test(tls): ensureHost is visible to the next TLS handshake without a restart
* docs(tls): custom domains learned at runtime
* test(tls): pin the certificate contracts of a runtime reissue
The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.
* fix(tls): retry a failed listener reload and keep served names across a boot
A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.
At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.
The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.
Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.
* fix(tls): carry a name whose reload failed into later reissues and resets
The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.
Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.
* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA
RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.
The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.
AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.
* refactor(acm): drop the cosmetic Amazon issuer generator
CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.
* docs(acm): certificates chain to the local CA
Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.
* test(acm): the SDK compatibility suite validates the certificate against its chain
GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.
* docs(acm): say when the CA is created and what Issuer reports
ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.
* test(acm): pin key size, an imported chain and the persisted chain
The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.
* test(acm): the python compatibility suite verifies the certificate against its chain
The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.
* fix(acm): write EC private keys as PKCS#8 and classify keys by interface
JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.
Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.
* test(acm): AcmServiceTest pins issuance from the local CA
Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.
* feat(apigateway): serve a custom domain over TLS as soon as it is created
CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.
* feat(iot): serve a customer-managed domain over TLS as soon as it is configured
CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.
* feat(cognito): serve a custom domain over TLS as soon as it is created
CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.
* docs: custom domains are served over TLS on creation
One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.
* test(compat): custom domain reachable over TLS trusting only the ACM chain
RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.
* docs(tls): say which ensureHost outcomes are logged as warnings
* test: pin the custom domain TLS hooks against the service contracts
Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.
* test(acm): build the InUseBy test service with the local CA
AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.
* test(cognito): request an issued ACM certificate in the custom domain TLS tests
Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.
* test(cognito): a concurrent create does not wait for the TLS reload
The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
|
||
|
|
ebdf092cce |
feat(iot): firehose and cloudwatchLogs rule actions (#3013)
* feat(iot): firehose and cloudwatchLogs rule actions
A topic rule can now deliver to a Kinesis Data Firehose delivery stream
(separator appended to each record, batchMode splitting a JSON array
into one record per element) and to CloudWatch Logs (one log event per
publish, or per array element with batchMode, in a stream named after
the rule that is created in the log group on first use).
* fix(iot): take timestamp and message from each batched cloudwatchLogs element and check the firehose separator
With batchMode the cloudwatchLogs action wrote every array element as one
log event whose message was the element's JSON text and whose timestamp was
the publish time. AWS requires a batched payload to be an array of
{"timestamp": <epoch ms>, "message": "<text>"} objects and takes both from
each element. The action now does the same; an element without a numeric
timestamp is stamped with the publish time and one without a message is
logged as its JSON text, so a batch that ignores the format still lands.
CreateTopicRule and ReplaceTopicRule reject a firehose separator that is
not a newline, tab, Windows newline or comma, the FirehoseSeparator pattern
of the IoT API model, with InvalidRequestException.
|
||
|
|
7ec4c89d0f |
fix(iot): isolate topic rule actions and run the error action (#3012)
* fix(iot): isolate topic rule actions and run the error action One failing action of a topic rule no longer fails the publish or the actions after it. The failure is logged, and once every action ran the rule's errorAction receives the AWS failure document (ruleName, topic, base64OriginalPayload, failures). CreateTopicRule and ReplaceTopicRule keep awsIotSqlVersion and errorAction, and GetTopicRule returns them. * fix(iot): map nested payload values to DynamoDB maps and lists in the dynamoDBv2 action Objects and arrays in a payload were flattened to empty strings, which also emptied the failures list of the error action's failure document. They now become DynamoDB M and L attribute values, as on AWS. * fix(iot): skip a topic rule action without a type and keep the stack trace of a failed action An action object without a recognisable member is skipped with a warning before anything is dispatched, so the failure document can never see a missing type, and the warnings for a failed action, error action or unparsable stored rule now carry the exception. |
||
|
|
9220c057b7 |
feat(iot): domain configurations (#3008)
* feat(iot): add the domain configuration model and service Stores AWS IoT Core domain configurations the way the API reports them: a new configuration is ENABLED and CUSTOMER_MANAGED (ENDPOINT without a domain name), carries one VALID server certificate, the default TLS policy and an ARN with the short id AWS appends. Update changes the status, authorizer, TLS, certificate and protocol settings; delete refuses an ENABLED configuration, as AWS does; list filters by service type and pages with marker and pageSize. Tags work on the ARN. * feat(iot): serve the domain configuration API Adds the REST-JSON routes CreateDomainConfiguration, DescribeDomainConfiguration, UpdateDomainConfiguration, DeleteDomainConfiguration and ListDomainConfigurations under /domainConfigurations, registered with the IoT service so the X-Amzn-Errortype header is set for unsigned callers too. Tags on a configuration ARN go through IotTagHandler; the IoT /untag route now uses the same handler as /tags instead of calling IotService directly. DescribeEndpoint accepts iot:CredentialProvider, the endpoint type that pairs with the CREDENTIAL_PROVIDER service type. * feat(iot): provision AWS::IoT::DomainConfiguration Adds IotDomainConfigurationCfnProvisioner over the domain configuration service. Ref is the configuration name; Fn::GetAtt Arn, DomainType and ServerCertificates resolve to what DescribeDomainConfiguration reports (ServerCertificates as a JSON string, since attributes are strings). Like the CloudFormation handler, a configuration is created ENABLED and a DomainConfigurationStatus of DISABLED is applied with a follow-up update; tags go through TagResource and are reconciled on update; a delete disables the configuration first because the API refuses to delete an ENABLED one. UpdateStack keeps the configuration when the createOnly properties (DomainName, ServiceType, ValidationCertificateArn, ServerCertificateArns) are unchanged and replaces it otherwise, with a fresh generated name when the template names none. Inventory TSV, fixture wiring and the generated resource-type table updated. * docs(iot): describe domain configurations and add the stack integration test IotDomainConfigurationCfnIntegrationTest provisions the type through a stack and asserts Ref and every Fn::GetAtt attribute against DescribeDomainConfiguration, the in-place status update, and that DeleteStack removes the configuration. * test(iot): cover domain configurations in the Java and Go SDK suites Both cases create, describe, list, update and delete a configuration through the real SDK clients and check the AWS error types on the duplicate create, the refused delete of an ENABLED configuration and the describe after deletion. * fix(iot): remove a renamed domain configuration and keep the status when the template omits it A template that changes DomainConfigurationName creates the new configuration and now removes the previous one, as the generated-name replacement already did; before, the old configuration outlived the stack. An update without DomainConfigurationStatus no longer forces ENABLED: the field is omitted and the current status stays, as the AWS handler does. The service rejects a structured JSON value where a string, boolean, list or object is expected instead of turning it into an empty string or silently clearing the authorizer, and validates the whole update before touching the stored record. * fix(iot): let stack rollback remove a domain configuration and make same-name creates atomic A configuration created by a stack is recorded, with the owned marker, before the follow-up status update, so a failure there still lets the create rollback delete it. A replacement that fails after the new configuration exists removes it again, re-enables the previous one if it had been disabled on the way out, and marks the resource restored, as the other provisioners do. CreateDomainConfiguration checks and stores the name in one step, so two overlapping creates of the same name cannot both succeed. A tags value that is not a list is rejected. The Java SDK compatibility case looks for a leftover configuration instead of swallowing every cleanup exception. * fix(iot): point the resource back at the prior domain configuration after a failed replacement After the unwind removes the replacement and re-enables the previous configuration, the resource now carries the previous name and attributes again, without the owned marker, so it describes the configuration that is still there rather than the one just removed. * feat(iot): serve the AWS-managed domain configurations Every AWS account has iot:Data-ATS, iot:Data, iot:CredentialProvider and iot:Jobs without creating them. They now exist in every region on first use: AWS_MANAGED, ENABLED, no server certificate, and the address DescribeEndpoint returns as their domain name. They can be updated and tagged like any other configuration, but not deleted, as on AWS. A client that starts by describing iot:Data-ATS gets an answer instead of a 404. * fix(iot): report a failed replacement cleanup as a rollback failure When the unwind of a failed replacement cannot remove the new domain configuration, the resource now carries the rollback-failure marker with the reason, so the stack ends in UPDATE_ROLLBACK_FAILED instead of reporting a clean rollback while the configuration is still there. The marker moves next to the restored one in CfnRollback so extracted provisioners can set it; the legacy provisioner keeps its alias. * fix(iot): serialise every read-modify-write on a domain configuration Update, delete, tag and untag read a record, change it and write it back. Two overlapping writers lost each other's changes: sixteen tag writers on one configuration left seven keys. All of them now run under the lock the create already used, and a test pins the invariant. A JSON round trip with the mapper setup persistent storage uses pins that the model reloads intact. * fix(iot): keep the prior status the unwind compares against and never delete a same-name replacement The store hands out its live record, so disabling the prior on the way to deleting it changed the very object the unwind later compared against, and a prior whose delete failed half way was left DISABLED while the stack reported a clean rollback. The status seen at the start is now kept and used. The test reproduces the aliasing instead of handing the provisioner a fresh copy per call. A replacement under the same explicit name normally fails on the create; if it goes through because the prior vanished in between, the prior is no longer deleted, which would have removed the configuration just created. * fix(iot): tolerate a domain configuration that vanishes while a stack delete disables it The disable that precedes the delete now treats ResourceNotFoundException as already deleted, the way the delete itself does. The SDK cases also enable an already ENABLED configuration, the call a client makes when it only wants to be sure the configuration is on. |
||
|
|
9b451ccc82 |
fix(iot): match topic rules outside the default region (#2169)
* fix(iot): match topic rules outside the default region Topic rules are stored per region — topicRuleKey(region, ruleName) — but handlePublish looked them up with a hardcoded config.defaultRegion(). A rule created in any other region was stored, gettable and listable yet never evaluated: republish/SQS/SNS/Kinesis/DynamoDB/Lambda actions were silently dropped while Publish still returned 200. IotDataController.publish now resolves the region from the request's SigV4 credential, as the shadow endpoints in that controller already do, and threads it through IotService.publish into handlePublish. A publish that carries no region — MQTT, or an unsigned data-plane request — evaluates every region's rules, mirroring the fallback ApiGatewayService.resolveRestApiRegion applies to unsigned REST API invocations. executeTopicRule derives the rule's own region from its ARN and targets the action sinks with it instead of the default region, so a rule created in eu-west-1 delivers to eu-west-1 resources. Closes #2065 * fix(iot): treat a non-SigV4 publish header as an unresolved region IotDataController.publish skipped region resolution only for a missing or blank Authorization header. Any other non-SigV4 value — a bearer JWT, say — fell through to resolveRegionFromAuth, whose miss path returns the configured default region. So a publish carrying such a header evaluated only the default region's rules, while one carrying no header at all evaluated every region's: the same absence of region information, two different outcomes. RegionResolver.resolveRegionFromAuthOrNull returns the credential's region, or null when there is nothing to parse, and publish threads that through — so every publish that names no region is treated the same way. |
||
|
|
326b495496 |
feat(iot) Feature/issue 1038 iot core (#1359)
* feat: add IoT endpoint and thing registry * feat: add IoT thing tagging * feat: add IoT certificates and shadows * feat: add IoT MQTT broker * feat: upgrade IoT MQTT broker to Moquette 0.18 * feat: restore IoT reserved MQTT topics * feat: add IoT topic rules engine * feat: improve IoT thing registry compatibility * feat: complete IoT MVP 1 compatibility * feat: complete IoT MVP 2 compatibility * feat: finish IoT MVP 2 coverage * fix: disable IoT MQTT broker persistence * fix(docker): include vendored Maven artifacts in source builds * fix(iot): stabilize MQTT integration test sockets * fix(iot): verify MQTT test connections * fix(iot): use Paho for MQTT integration tests * fix(iot): use Vert.x MQTT broker --------- Co-authored-by: nathan <nathan@debian-dev-small.localdomain> |