From b4d3865386dd7bd87483774e8c2170ddbedf32f1 Mon Sep 17 00:00:00 2001 From: Cameron Reeves Date: Wed, 7 Oct 2026 14:45:06 +1100 Subject: [PATCH 01/50] feat: PPT-2701 organisation reach enforcement Resolve the caller's reach once per request (cluster, partner or organisation, widened by live grants) and keep every estate list, lookup and mutation inside it. PLACE_TENANCY_ENFORCE switches between refusing and logging what would be refused. Adds organisations, partners and grants routes, builds against the models PPT-526-partner-client branch. --- shard.override.yml | 8 +- spec/controllers/tenancy_spec.cr | 253 ++++++++++++++++ spec/helper.cr | 7 + spec/migration/Dockerfile | 3 +- spec/spec_helpers/tenancy.cr | 119 ++++++++ src/constants.cr | 3 + src/placeos-rest-api/controllers/api_keys.cr | 10 +- .../controllers/application.cr | 3 + .../controllers/authentications.cr | 8 +- src/placeos-rest-api/controllers/brokers.cr | 2 + .../controllers/build_monitor.cr | 1 + src/placeos-rest-api/controllers/cluster.cr | 1 + src/placeos-rest-api/controllers/domains.cr | 26 +- src/placeos-rest-api/controllers/drivers.cr | 2 + src/placeos-rest-api/controllers/edges.cr | 11 +- src/placeos-rest-api/controllers/grants.cr | 105 +++++++ src/placeos-rest-api/controllers/metadata.cr | 12 + src/placeos-rest-api/controllers/modules.cr | 25 +- .../controllers/oauth_applications.cr | 7 +- .../controllers/organisations.cr | 171 +++++++++++ src/placeos-rest-api/controllers/partners.cr | 74 +++++ .../controllers/repositories.cr | 2 + src/placeos-rest-api/controllers/schema.cr | 1 + src/placeos-rest-api/controllers/settings.cr | 8 +- .../controllers/system-triggers.cr | 8 +- src/placeos-rest-api/controllers/systems.cr | 52 +++- .../controllers/tenant_consent.cr | 1 + src/placeos-rest-api/controllers/triggers.cr | 30 +- src/placeos-rest-api/controllers/users.cr | 13 +- src/placeos-rest-api/controllers/zones.cr | 36 ++- src/placeos-rest-api/utilities/tenancy.cr | 269 ++++++++++++++++++ src/placeos-rest-api/websocket/manager.cr | 3 +- src/placeos-rest-api/websocket/session.cr | 22 ++ 33 files changed, 1247 insertions(+), 49 deletions(-) create mode 100644 spec/controllers/tenancy_spec.cr create mode 100644 spec/spec_helpers/tenancy.cr create mode 100644 src/placeos-rest-api/controllers/grants.cr create mode 100644 src/placeos-rest-api/controllers/organisations.cr create mode 100644 src/placeos-rest-api/controllers/partners.cr create mode 100644 src/placeos-rest-api/utilities/tenancy.cr diff --git a/shard.override.yml b/shard.override.yml index 4667f5a5..2a60a444 100644 --- a/shard.override.yml +++ b/shard.override.yml @@ -18,7 +18,7 @@ dependencies: github: place-labs/ulid branch: master - # uncomment to test different model branches - # placeos-models: - # github: placeos/models - # branch: add-signage-groups + # PPT-526: build against the multi-tenancy data layer until models #332 merges + placeos-models: + github: placeos/models + branch: PPT-526-partner-client diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr new file mode 100644 index 00000000..407911ab --- /dev/null +++ b/spec/controllers/tenancy_spec.cr @@ -0,0 +1,253 @@ +require "../helper" + +private def tenancy_get(path, user) + client.get(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user)) +end + +private def tenancy_post(path, user, body) + client.post(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user), body: body.to_json) +end + +module PlaceOS::Api + # PPT-526: who can see and touch what across organisations on a shared cluster + describe "tenancy" do + before_each { Utils::Tenancy.enforce = true } + after_each { Utils::Tenancy.enforce = false } + + describe "reach" do + it "resolves cluster, partner and organisation reach" do + f = Spec::Tenancy.build + + cluster = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.placeos.admin).body) + cluster["reach"].should eq "cluster" + cluster["enforcing"].as_bool.should be_true + cluster["organisations"].raw.should be_nil + + partner = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.ntt_staff.admin).body) + partner["reach"].should eq "partner" + partner["organisations"].as_a.map(&.["id"].to_s).sort!.should eq [f.ntt_staff.organisation.id.to_s, f.acadian.organisation.id.to_s].sort + + org = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.acadian.admin).body) + org["reach"].should eq "organisation" + org["organisations"].as_a.map(&.["id"].to_s).should eq [f.acadian.organisation.id.to_s] + + plain = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.placeos.user).body) + plain["reach"].should eq "organisation" + end + end + + describe "estate lists" do + it "scopes zones, systems and modules to the caller's organisations" do + f = Spec::Tenancy.build + + zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.acadian.admin).body) + zones.should contain(f.acadian.org_zone.id) + zones.should_not contain(f.ucla.org_zone.id) + zones.should_not contain(f.unowned_zone.id) + + partner_zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.ntt_staff.support).body) + partner_zones.should contain(f.acadian.org_zone.id) + partner_zones.should contain(f.ntt_staff.org_zone.id) + partner_zones.should_not contain(f.ucla.org_zone.id) + + cluster_zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.placeos.admin).body) + cluster_zones.should contain(f.ucla.org_zone.id) + cluster_zones.should contain(f.unowned_zone.id) + + systems = Spec::Tenancy.ids(tenancy_get(Systems.base_route, f.ucla.admin).body) + systems.should eq [f.ucla.system.id] + + modules = Spec::Tenancy.ids(tenancy_get(Modules.base_route, f.ucla.admin).body) + modules.should eq [f.ucla.mod.id] + + tenancy_get("#{Zones.base_route}tags", f.acadian.admin).status_code.should eq 200 + end + + it "answers 404 for another organisation's rows and 200 for its own" do + f = Spec::Tenancy.build + + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.acadian.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.acadian.admin).status_code.should eq 200 + tenancy_get("#{Systems.base_route}#{f.ucla.system.id}", f.acadian.admin).status_code.should eq 404 + tenancy_get("#{Modules.base_route}#{f.ucla.mod.id}", f.acadian.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.acadian.admin).status_code.should eq 404 + + # partner staff reach their client, not a stranger + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ntt_staff.admin).status_code.should eq 200 + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.ntt_staff.admin).status_code.should eq 404 + + # cluster admins reach everything, unowned rows included + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.placeos.admin).status_code.should eq 200 + tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.placeos.admin).status_code.should eq 200 + end + + it "only logs when enforcement is off" do + f = Spec::Tenancy.build + Utils::Tenancy.enforce = false + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.acadian.admin).status_code.should eq 200 + end + end + + describe "estate writes" do + it "owns new zones through the caller or the parent" do + f = Spec::Tenancy.build + + root = tenancy_post(Zones.base_route, f.acadian.admin, {name: "Acadian root #{random_name}", tags: ["building"]}) + root.status_code.should eq 201 + JSON.parse(root.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s + + child = tenancy_post(Zones.base_route, f.acadian.admin, {name: "Level #{random_name}", parent_id: f.acadian.building.id}) + child.status_code.should eq 201 + JSON.parse(child.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s + + foreign_parent = tenancy_post(Zones.base_route, f.acadian.admin, {name: "Sneaky #{random_name}", parent_id: f.ucla.building.id}) + foreign_parent.status_code.should eq 404 + + named = client.post("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.placeos.admin), body: {name: "UCLA root #{random_name}", tags: ["building"]}.to_json) + named.status_code.should eq 201 + JSON.parse(named.body)["organisation_id"].to_s.should eq f.ucla.organisation.id.to_s + + client.post("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "Not mine #{random_name}"}.to_json).status_code.should eq 403 + end + + it "owns new systems through their zones and refuses mixed zones" do + f = Spec::Tenancy.build + + own = tenancy_post(Systems.base_route, f.acadian.admin, {name: "Room #{random_name}", zones: [f.acadian.building.id]}) + own.status_code.should eq 201 + JSON.parse(own.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s + + tenancy_post(Systems.base_route, f.acadian.admin, {name: "Room #{random_name}", zones: [f.ucla.building.id]}).status_code.should eq 404 + + mixed = tenancy_post(Systems.base_route, f.placeos.admin, {name: "Room #{random_name}", zones: [f.acadian.building.id, f.ucla.building.id]}) + mixed.status_code.should eq 422 + end + + it "keeps modules inside the system's organisation" do + f = Spec::Tenancy.build + + attach = client.put("#{Systems.base_route}#{f.acadian.system.id}/module/#{f.ucla.mod.id}", headers: Spec::Tenancy.headers(f.acadian.admin)) + attach.status_code.should eq 404 + + attach = client.put("#{Systems.base_route}#{f.ucla.system.id}/module/#{f.ucla.mod.id}", headers: Spec::Tenancy.headers(f.ucla.admin)) + attach.status_code.should eq 200 + end + end + + describe "domains and users" do + it "lists and creates domains within reach" do + f = Spec::Tenancy.build + + domains = Spec::Tenancy.ids(tenancy_get(Domains.base_route, f.acadian.admin).body) + domains.should eq [f.acadian.authority.id] + tenancy_get("#{Domains.base_route}#{f.ucla.authority.id}", f.acadian.admin).status_code.should eq 404 + + created = tenancy_post(Domains.base_route, f.acadian.admin, {name: "Acadian two", domain: "two.acadian.test"}) + created.status_code.should eq 201 + JSON.parse(created.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s + + staff = client.post("#{Domains.base_route}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.placeos.admin), body: {name: "UCLA two", domain: "two.ucla.test"}.to_json) + staff.status_code.should eq 201 + JSON.parse(staff.body)["organisation_id"].to_s.should eq f.ucla.organisation.id.to_s + + moved = client.patch("#{Domains.base_route}#{f.acadian.authority.id}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "renamed"}.to_json) + moved.status_code.should eq 403 + end + + it "lists users within reach only" do + f = Spec::Tenancy.build + + users = Spec::Tenancy.ids(tenancy_get(Users.base_route, f.acadian.admin).body) + users.should contain(f.acadian.user.id) + users.should_not contain(f.ucla.user.id) + + tenancy_get("#{Users.base_route}?authority_id=#{f.ucla.authority.id}", f.acadian.admin).status_code.should eq 404 + tenancy_get("#{Users.base_route}#{f.ucla.user.id}", f.acadian.admin).status_code.should eq 404 + + partner_users = Spec::Tenancy.ids(tenancy_get(Users.base_route, f.ntt_staff.admin).body) + partner_users.should contain(f.acadian.user.id) + partner_users.should_not contain(f.ucla.user.id) + end + end + + describe "cluster-only resources" do + it "hides brokers and trigger templates' writes from organisation admins" do + f = Spec::Tenancy.build + + tenancy_get(Brokers.base_route, f.acadian.admin).status_code.should eq 403 + tenancy_get(Brokers.base_route, f.placeos.admin).status_code.should eq 200 + + template = tenancy_post(Triggers.base_route, f.acadian.admin, {name: "Template #{random_name}"}) + template.status_code.should eq 403 + template = tenancy_post(Triggers.base_route, f.placeos.admin, {name: "Template #{random_name}"}) + template.status_code.should eq 201 + + # templates are readable by every organisation + templates = Spec::Tenancy.ids(tenancy_get(Triggers.base_route, f.acadian.admin).body) + templates.should contain(JSON.parse(template.body)["id"].to_s) + + bound = tenancy_post(Triggers.base_route, f.acadian.admin, {name: "Bound #{random_name}", control_system_id: f.acadian.system.id}) + bound.status_code.should eq 201 + JSON.parse(bound.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s + Spec::Tenancy.ids(tenancy_get(Triggers.base_route, f.ucla.admin).body).should_not contain(JSON.parse(bound.body)["id"].to_s) + end + end + + describe "organisations, partners and grants" do + it "lets cluster admins manage the hierarchy and others read their own" do + f = Spec::Tenancy.build + + partner = tenancy_post(Partners.base_route, f.placeos.admin, {name: "Integrator #{random_name}"}) + partner.status_code.should eq 201 + partner_id = JSON.parse(partner.body)["id"].to_s + + organisation = client.post("#{Organisations.base_route}?partner_staff=true", headers: Spec::Tenancy.headers(f.placeos.admin), body: {name: "Integrator staff #{random_name}", partner_id: partner_id}.to_json) + organisation.status_code.should eq 201 + JSON.parse(organisation.body)["partner_staff"].as_bool.should be_true + + tenancy_post(Partners.base_route, f.acadian.admin, {name: "Nope #{random_name}"}).status_code.should eq 403 + + Spec::Tenancy.ids(tenancy_get(Organisations.base_route, f.acadian.admin).body).should eq [f.acadian.organisation.id.to_s] + Spec::Tenancy.ids(tenancy_get(Partners.base_route, f.acadian.admin).body).should eq [f.ntt.id.to_s] + tenancy_get("#{Partners.base_route}#{f.management.id}", f.acadian.admin).status_code.should eq 404 + + client.patch("#{Organisations.base_route}#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "renamed"}.to_json).status_code.should eq 403 + end + + it "widens reach through live grants" do + f = Spec::Tenancy.build + + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + + granted = tenancy_post(Grants.base_route, f.placeos.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: 1}) + granted.status_code.should eq 201 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 200 + + client.delete("#{Grants.base_route}#{JSON.parse(granted.body)["id"]}", headers: Spec::Tenancy.headers(f.placeos.admin)).status_code.should eq 202 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + + expired = tenancy_post(Grants.base_route, f.placeos.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: 1, expires_at: 1.hour.ago}) + expired.status_code.should eq 201 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + + # an organisation admin may grant into their own organisation but not a stranger's + tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s}).status_code.should eq 201 + tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.acadian.admin.id, scope_type: "organisation", scope_id: f.ucla.organisation.id.to_s}).status_code.should eq 403 + end + + it "claims an unowned zone tree for an organisation" do + f = Spec::Tenancy.build + + claimed = tenancy_post("#{Organisations.base_route}#{f.ucla.organisation.id}/claim", f.placeos.admin, {zone_ids: [f.unowned_zone.id]}) + claimed.status_code.should eq 200 + result = JSON.parse(claimed.body) + result["zones"].should eq 1 + result["systems"].should eq 1 + + Model::Zone.find!(f.unowned_zone.id.as(String)).organisation_id.should eq f.ucla.organisation.id + Model::ControlSystem.find!(f.unowned_system.id.as(String)).organisation_id.should eq f.ucla.organisation.id + tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.ucla.admin).status_code.should eq 200 + end + end + end +end diff --git a/spec/helper.cr b/spec/helper.cr index 2f4b83f8..943fc363 100644 --- a/spec/helper.cr +++ b/spec/helper.cr @@ -94,6 +94,13 @@ def clear_tables PlaceOS::Model::Storage, PlaceOS::Model::DoorkeeperApplication, ].each(&.clear) + + # Tenancy rows go last: the estate tables above RESTRICT on organisations. + PlaceOS::Model::Edge.clear + PlaceOS::Model::Broker.clear + PlaceOS::Model::Grant.clear + PlaceOS::Model::Organisation.clear + PlaceOS::Model::Partner.clear end def random_name diff --git a/spec/migration/Dockerfile b/spec/migration/Dockerfile index 11531ab8..76b4070f 100644 --- a/spec/migration/Dockerfile +++ b/spec/migration/Dockerfile @@ -5,7 +5,8 @@ WORKDIR /app COPY . /app # NOTE:: add `--branch my-new-model-branch` if you want to test a particular branch -RUN git clone https://github.com/PlaceOS/models +# PPT-526: the tenancy migrations live on this branch until models #332 merges +RUN git clone --branch PPT-526-partner-client https://github.com/PlaceOS/models RUN mv ./models/migration/db ./db ENV PATH /app/bin:$PATH diff --git a/spec/spec_helpers/tenancy.cr b/spec/spec_helpers/tenancy.cr new file mode 100644 index 00000000..c289e983 --- /dev/null +++ b/spec/spec_helpers/tenancy.cr @@ -0,0 +1,119 @@ +require "placeos-models/spec/generator" + +module PlaceOS::Api::Spec::Tenancy + # One customer organisation with a domain, three users and a small estate + record Org, + organisation : Model::Organisation, + authority : Model::Authority, + admin : Model::User, + support : Model::User, + user : Model::User, + org_zone : Model::Zone, + building : Model::Zone, + system : Model::ControlSystem, + mod : Model::Module + + # The shape of a shared cluster: PlaceOS staff on localhost (cluster reach), + # NTT as a partner with its own staff organisation and one client (Acadian), + # UCLA as a direct customer, and an unowned zone tree. + record Fixture, + management : Model::Partner, + placeos : Org, + ntt : Model::Partner, + ntt_staff : Org, + acadian : Org, + ucla : Org, + unowned_zone : Model::Zone, + unowned_system : Model::ControlSystem + + def self.build : Fixture + management = Model::Generator.partner(management: true).save! + ntt = Model::Generator.partner.save! + + placeos = org("localhost", Model::Generator.organisation(partner: management, partner_staff: true).save!) + ntt_staff = org("ntt.test", Model::Generator.organisation(partner: ntt, partner_staff: true).save!) + acadian = org("acadian.test", Model::Generator.organisation(partner: ntt).save!) + ucla = org("ucla.test", Model::Generator.organisation.save!) + + unowned_zone = Model::Generator.zone.tap { |z| z.name = "Unowned #{random_name}"; z.tags = Set{"org"} }.save! + unowned_system = Model::Generator.control_system.tap do |sys| + sys.name = "Unowned room #{random_name}" + sys.zones = [unowned_zone.id.as(String)] + end.save! + + Fixture.new(management, placeos, ntt, ntt_staff, acadian, ucla, unowned_zone, unowned_system) + end + + def self.org(domain : String, organisation : Model::Organisation) : Org + authority = Model::Authority.find_by_domain(domain) || Model::Generator.authority(domain) + authority.domain = domain + authority.organisation_id = organisation.id + authority.save! + + org_zone = Model::Generator.zone.tap do |z| + z.name = "ORG #{organisation.name}" + z.tags = Set{"org"} + z.organisation_id = organisation.id + end.save! + authority.config_will_change! + authority.config["org_zone"] = JSON::Any.new(org_zone.id.as(String)) + authority.save! + + building = Model::Generator.zone.tap do |z| + z.name = "Building #{organisation.name}" + z.tags = Set{"building"} + z.parent_id = org_zone.id + z.organisation_id = organisation.id + end.save! + + system = Model::Generator.control_system.tap do |sys| + sys.name = "Room #{organisation.name}" + sys.zones = [org_zone.id.as(String), building.id.as(String)] + sys.organisation_id = organisation.id + end.save! + + mod = Model::Generator.module(control_system: system).tap(&.organisation_id = organisation.id).save! + system.modules = [mod.id.as(String)] + system.save! + + Org.new( + organisation: organisation, + authority: authority, + admin: Model::Generator.user(authority, admin: true).save!, + support: Model::Generator.user(authority, support: true).save!, + user: Model::Generator.user(authority).save!, + org_zone: org_zone, + building: building, + system: system, + mod: mod, + ) + end + + # Bearer + Host headers for a user on their own domain + def self.headers(user : Model::User) : HTTP::Headers + authority = user.authority.as(Model::Authority) + permissions = case {user.support, user.sys_admin} + when {true, true} then Model::UserJWT::Permissions::AdminSupport + when {true, false} then Model::UserJWT::Permissions::Support + when {false, true} then Model::UserJWT::Permissions::Admin + else Model::UserJWT::Permissions::User + end + jwt = Model::UserJWT.new( + iss: Model::UserJWT::ISSUER, + iat: 5.minutes.ago, + exp: 1.hour.from_now, + domain: authority.domain, + id: user.id.as(String), + user: Model::UserJWT::Metadata.new(name: user.name.as(String), email: user.email.to_s, permissions: permissions), + ) + HTTP::Headers{ + "Authorization" => "Bearer #{jwt.encode}", + "Content-Type" => "application/json", + "Host" => authority.domain, + } + end + + def self.ids(body : String) : Array(String) + Array(Hash(String, JSON::Any)).from_json(body).map(&.["id"].to_s) + end +end diff --git a/src/constants.cr b/src/constants.cr index 0f5b2d67..6abb3acc 100644 --- a/src/constants.cr +++ b/src/constants.cr @@ -9,6 +9,9 @@ module PlaceOS::Api BUILD_TIME = {{ system("date -u").stringify }} BUILD_COMMIT = {{ env("PLACE_COMMIT") || "DEV" }} + # PPT-526: refuse cross-organisation access (true) or only log what would be refused (false) + PLACE_TENANCY_ENFORCE = ENV["PLACE_TENANCY_ENFORCE"]?.try(&.downcase).in?("true", "1", "yes") || false + PLACE_DISPATCH_HOST = ENV["PLACE_DISPATCH_HOST"]? || "dispatch" PLACE_DISPATCH_PORT = (ENV["PLACE_DISPATCH_PORT"]? || "3000").to_i diff --git a/src/placeos-rest-api/controllers/api_keys.cr b/src/placeos-rest-api/controllers/api_keys.cr index 9c954258..c7ec765c 100644 --- a/src/placeos-rest-api/controllers/api_keys.cr +++ b/src/placeos-rest-api/controllers/api_keys.cr @@ -19,7 +19,9 @@ module PlaceOS::Api def find_current_api_key(id : String) Log.context.set(api_key: id) # Find will raise a 404 (not found) if there is an error - @current_api_key = ::PlaceOS::Model::ApiKey.find!(id) + api_key = ::PlaceOS::Model::ApiKey.find!(id) + ensure_authority_reach!(api_key.authority_id, "api key") + @current_api_key = api_key end getter! current_api_key : ::PlaceOS::Model::ApiKey @@ -33,9 +35,10 @@ module PlaceOS::Api authority_id : String? = nil, ) : Array(::PlaceOS::Model::ApiKey::PublicResponse) # PG full-text search (PPT-2644) - query = ::PlaceOS::Model::ApiKey.all + query = scope_authorities(::PlaceOS::Model::ApiKey.all) if authority = authority_id + ensure_authority_reach!(authority, "domain") query = query.where(authority_id: authority) end @@ -61,6 +64,9 @@ module PlaceOS::Api # create a new API key @[AC::Route::POST("/", body: :api_key, status_code: HTTP::Status::CREATED)] def create(api_key : ::PlaceOS::Model::ApiKey) : ::PlaceOS::Model::ApiKey::PublicResponse + if user_id = api_key.user_id + ensure_authority_reach!(::PlaceOS::Model::User.find!(user_id).authority_id, "user") + end raise Error::ModelValidation.new(api_key.errors) unless api_key.save api_key.to_public_struct end diff --git a/src/placeos-rest-api/controllers/application.cr b/src/placeos-rest-api/controllers/application.cr index cfaa8849..3dcec77b 100644 --- a/src/placeos-rest-api/controllers/application.cr +++ b/src/placeos-rest-api/controllers/application.cr @@ -38,6 +38,9 @@ module PlaceOS::Api # Helpers for defining scope checks on controller actions include Utils::Scopes + # Helpers for organisation reach (PPT-526 multi-tenancy) + include Utils::Tenancy + # for converting comma seperated lists # i.e. `"id-1,id-2,id-3"`, or a JSON array `["id-1","id-2"]` struct ConvertStringArray diff --git a/src/placeos-rest-api/controllers/authentications.cr b/src/placeos-rest-api/controllers/authentications.cr index c56a71ec..a7ac9e63 100644 --- a/src/placeos-rest-api/controllers/authentications.cr +++ b/src/placeos-rest-api/controllers/authentications.cr @@ -22,7 +22,9 @@ module PlaceOS::Api def find_current_auth(id : String) Log.context.set({{auth_type.id.underscore}}_id: id) # Find will raise a 404 (not found) if there is an error - @current_auth = ::PlaceOS::Model::{{auth_type.id}}Authentication.find!(id) + auth = ::PlaceOS::Model::{{auth_type.id}}Authentication.find!(id) + ensure_authority_reach!(auth.authority_id, "authentication") + @current_auth = auth end getter! current_auth : ::PlaceOS::Model::{{auth_type.id}}Authentication @@ -36,9 +38,10 @@ module PlaceOS::Api authority_id : String? = nil, ) : Array(::PlaceOS::Model::{{auth_type.id}}Authentication) # PG full-text search (PPT-2644) - query = ::PlaceOS::Model::{{auth_type.id}}Authentication.all + query = scope_authorities(::PlaceOS::Model::{{auth_type.id}}Authentication.all) if authority = authority_id + ensure_authority_reach!(authority, "domain") query = query.where(authority_id: authority) end @@ -64,6 +67,7 @@ module PlaceOS::Api # creates a new authentication method @[AC::Route::POST("/", body: :auth, status_code: HTTP::Status::CREATED)] def create(auth : ::PlaceOS::Model::{{auth_type.id}}Authentication) : ::PlaceOS::Model::{{auth_type.id}}Authentication + ensure_authority_reach!(auth.authority_id, "domain") raise Error::ModelValidation.new(auth.errors) unless auth.save auth end diff --git a/src/placeos-rest-api/controllers/brokers.cr b/src/placeos-rest-api/controllers/brokers.cr index 4ab9f934..f365197a 100644 --- a/src/placeos-rest-api/controllers/brokers.cr +++ b/src/placeos-rest-api/controllers/brokers.cr @@ -15,6 +15,8 @@ module PlaceOS::Api before_action :check_admin, except: [:collection, :show] before_action :check_support, only: [:collection, :show] + # brokers are cluster infrastructure + before_action :check_cluster_admin ############################################################################################### diff --git a/src/placeos-rest-api/controllers/build_monitor.cr b/src/placeos-rest-api/controllers/build_monitor.cr index cec327d5..706251ce 100644 --- a/src/placeos-rest-api/controllers/build_monitor.cr +++ b/src/placeos-rest-api/controllers/build_monitor.cr @@ -15,6 +15,7 @@ module PlaceOS::Api before_action :can_write, only: [:cancel] before_action :check_admin, only: [:cancel] + before_action :check_cluster_admin, only: [:cancel] ############################################################################################### diff --git a/src/placeos-rest-api/controllers/cluster.cr b/src/placeos-rest-api/controllers/cluster.cr index 28334958..dd135a23 100644 --- a/src/placeos-rest-api/controllers/cluster.cr +++ b/src/placeos-rest-api/controllers/cluster.cr @@ -12,6 +12,7 @@ module PlaceOS::Api ############################################################################################### before_action :check_admin + before_action :check_cluster_admin before_action :can_read, only: [:nodes, :show] before_action :can_write, only: [:destroy] diff --git a/src/placeos-rest-api/controllers/domains.cr b/src/placeos-rest-api/controllers/domains.cr index 6d7c0392..b757eb26 100644 --- a/src/placeos-rest-api/controllers/domains.cr +++ b/src/placeos-rest-api/controllers/domains.cr @@ -20,7 +20,9 @@ module PlaceOS::Api def find_current_domain(id : String) Log.context.set(authority_id: id) # Find will raise a 404 (not found) if there is an error - @current_domain = ::PlaceOS::Model::Authority.find!(id) + domain = ::PlaceOS::Model::Authority.find!(id) + ensure_reach!(domain) + @current_domain = domain end getter! current_domain : ::PlaceOS::Model::Authority @@ -31,7 +33,7 @@ module PlaceOS::Api @[AC::Route::GET("/")] def index : Array(::PlaceOS::Model::Authority) # PG full-text search (PPT-2644) - paginate_search(::PlaceOS::Model::Authority.all, ::PlaceOS::Model::Authority.table_name) + paginate_search(scope_organisations(::PlaceOS::Model::Authority.all), ::PlaceOS::Model::Authority.table_name) end # skip authentication for the lookup @@ -59,16 +61,30 @@ module PlaceOS::Api # udpate a domains details @[AC::Route::PATCH("/:id", body: :domain)] @[AC::Route::PUT("/:id", body: :domain)] - def update(domain : ::PlaceOS::Model::Authority) : ::PlaceOS::Model::Authority + def update( + domain : ::PlaceOS::Model::Authority, + @[AC::Param::Info(description: "move the domain to this organisation (cluster admins only)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : ::PlaceOS::Model::Authority current = current_domain current.assign_attributes(domain) + if organisation_id + check_cluster_admin + current.organisation_id = organisation_id + end raise Error::ModelValidation.new(current.errors) unless current.save current end - # add a new domain + # add a new domain. Organisation admins create domains in their own + # organisation; cluster admins name the organisation. @[AC::Route::POST("/", body: :domain, status_code: HTTP::Status::CREATED)] - def create(domain : ::PlaceOS::Model::Authority) : ::PlaceOS::Model::Authority + def create( + domain : ::PlaceOS::Model::Authority, + @[AC::Param::Info(description: "the organisation that owns the new domain", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : ::PlaceOS::Model::Authority + domain.organisation_id = organisation_for_new_row(organisation_id) raise Error::ModelValidation.new(domain.errors) unless domain.save domain end diff --git a/src/placeos-rest-api/controllers/drivers.cr b/src/placeos-rest-api/controllers/drivers.cr index f302fa1b..75ae0557 100644 --- a/src/placeos-rest-api/controllers/drivers.cr +++ b/src/placeos-rest-api/controllers/drivers.cr @@ -13,6 +13,8 @@ module PlaceOS::Api before_action :can_write, only: [:create, :update, :destroy, :remove] before_action :check_admin, except: [:index, :show, :readme] + # drivers are shared by every organisation; only cluster admins change them + before_action :check_cluster_admin, except: [:index, :show, :readme] # Restrict driver listing and readme access to admin/support. These # endpoints expose internal infrastructure detail (driver inventory, driver diff --git a/src/placeos-rest-api/controllers/edges.cr b/src/placeos-rest-api/controllers/edges.cr index 11a0f814..173bbd7c 100644 --- a/src/placeos-rest-api/controllers/edges.cr +++ b/src/placeos-rest-api/controllers/edges.cr @@ -34,9 +34,14 @@ module PlaceOS::Api def find_current_edge(id : String) Log.context.set(edge_id: id) # Find will raise a 404 (not found) if there is an error - @current_edge = ::PlaceOS::Model::Edge.find!(id) + edge = ::PlaceOS::Model::Edge.find!(id) + ensure_reach!(edge) + @current_edge = edge end + # Fleet-wide monitoring spans every organisation + before_action :check_cluster_admin, only: [:edges_health, :edges_errors, :edges_connections, :edges_module_failures, :edges_statistics, :edges_error_stream, :edges_module_stream, :cleanup_errors, :monitoring_summary] + getter! current_edge : ::PlaceOS::Model::Edge ############################################################################################### @@ -70,7 +75,7 @@ module PlaceOS::Api @[AC::Route::GET("/")] def index : Array(::PlaceOS::Model::Edge) # PG full-text search (PPT-2644) - paginate_search(::PlaceOS::Model::Edge.all, ::PlaceOS::Model::Edge.table_name) + paginate_search(scope_organisations(::PlaceOS::Model::Edge.all), ::PlaceOS::Model::Edge.table_name) end # return the details of an edge location @@ -93,11 +98,13 @@ module PlaceOS::Api @[AC::Route::POST("/", body: :create_body, status_code: HTTP::Status::CREATED)] def create(create_body : ::PlaceOS::Model::Edge::CreateBody) : ::PlaceOS::Model::Edge::KeyResponse user = ::PlaceOS::Model::User.find!(create_body.user_id || current_user.id.as(String)) + ensure_authority_reach!(user.authority_id, "user") new_edge = ::PlaceOS::Model::Edge.for_user( user: user, name: create_body.name, description: create_body.description ) + new_edge.organisation_id = ::PlaceOS::Model::Authority.find?(user.authority_id.as(String)).try(&.organisation_id) # Ensure instance variable initialised new_edge.x_api_key diff --git a/src/placeos-rest-api/controllers/grants.cr b/src/placeos-rest-api/controllers/grants.cr new file mode 100644 index 00000000..63be43d5 --- /dev/null +++ b/src/placeos-rest-api/controllers/grants.cr @@ -0,0 +1,105 @@ +require "placeos-models/grant" + +require "./application" + +module PlaceOS::Api + # Grants: explicit, revocable, optionally time-boxed reach for a user into a + # partner, organisation or domain they do not belong to (PPT-526) + class Grants < Application + base "/api/engine/v2/grants/" + + # Scopes + ############################################################################################### + + before_action :can_read, only: [:index, :show] + before_action :can_write, only: [:create, :destroy] + + before_action :check_admin + + ############################################################################################### + + @[AC::Route::Filter(:before_action, except: [:index, :create])] + def find_current_grant(id : UUID) + Log.context.set(grant_id: id.to_s) + grant = ::PlaceOS::Model::Grant.find!(id) + ensure_scope_reach!(grant.scope_type, grant.scope_id) + @current_grant = grant + end + + getter! current_grant : ::PlaceOS::Model::Grant + + # Cluster admins manage every scope; organisation admins manage grants + # into their own organisation and its domains; partner admins request + # rather than self-grant + protected def ensure_scope_reach!(scope_type : String, scope_id : String) : Nil + return if tenancy.cluster? + own = tenancy.organisation_id + allowed = case scope_type + when ::PlaceOS::Model::Grant::SCOPE_ORGANISATION + own && own.to_s == scope_id + when ::PlaceOS::Model::Grant::SCOPE_AUTHORITY + own && ::PlaceOS::Model::Authority.find?(scope_id).try(&.organisation_id) == own + else + false + end + return if allowed + log_would_refuse("grant scope outside reach") + raise Error::Forbidden.new if Utils::Tenancy.enforce? + end + + ############################################################################################### + + # grants on a scope, or held by a user + @[AC::Route::GET("/")] + def index( + @[AC::Param::Info(description: "partner, organisation or authority", example: "organisation")] + scope_type : String? = nil, + @[AC::Param::Info(description: "the id of the partner, organisation or domain", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + scope_id : String? = nil, + @[AC::Param::Info(description: "grants held by this user", example: "user-1234")] + user_id : String? = nil, + ) : Array(::PlaceOS::Model::Grant) + query = ::PlaceOS::Model::Grant.all + if scope_type && scope_id + ensure_scope_reach!(scope_type, scope_id) + query = query.where(scope_type: scope_type, scope_id: scope_id) + elsif user_id + ensure_authority_reach!(::PlaceOS::Model::User.find!(user_id).authority_id, "user") + query = query.where(user_id: user_id) + else + check_cluster_admin + end + paginate_sql(query.order("created_at, id"), ::PlaceOS::Model::Grant.table_name, limit: search_limit, offset: search_offset) + end + + @[AC::Route::GET("/:id")] + def show : ::PlaceOS::Model::Grant + current_grant + end + + record GrantBody, user_id : String, scope_type : String, scope_id : String, permissions : Int32 = 1, expires_at : Time? = nil do + include JSON::Serializable + end + + @[AC::Route::POST("/", body: :body, status_code: HTTP::Status::CREATED)] + def create(body : GrantBody) : ::PlaceOS::Model::Grant + ensure_scope_reach!(body.scope_type, body.scope_id) + ::PlaceOS::Model::User.find!(body.user_id) + grant = ::PlaceOS::Model::Grant.new( + user_id: body.user_id, + scope_type: body.scope_type, + scope_id: body.scope_id, + permissions: body.permissions, + expires_at: body.expires_at, + granted_by: current_user.id, + ) + raise Error::ModelValidation.new(grant.errors) unless grant.save + grant + end + + @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] + def destroy : Nil + current_grant.destroy + end + end +end diff --git a/src/placeos-rest-api/controllers/metadata.cr b/src/placeos-rest-api/controllers/metadata.cr index ea36900d..ce486a7f 100644 --- a/src/placeos-rest-api/controllers/metadata.cr +++ b/src/placeos-rest-api/controllers/metadata.cr @@ -26,10 +26,20 @@ module PlaceOS::Api @[AC::Param::Info(name: "id", description: "the parent id of the metadata to be destroyed")] parent_id : String, ) + ensure_parent_reach!(parent_id) unless parent_id == user_token.id return if user_support? || parent_id == user_token.id check_access_level(parent_id, admin_required: true) end + # Every parent-addressed read and write stays inside the caller's reach + @[AC::Route::Filter(:before_action, only: [:show, :children_metadata, :update, :merge, :rename, :history])] + def check_parent_reach( + @[AC::Param::Info(name: "id", description: "the parent id of the metadata")] + parent_id : String, + ) + ensure_parent_reach!(parent_id) unless parent_id == user_token.id + end + ############################################################################################### # Fetch metadata with a specific name for multiple resources @@ -54,6 +64,8 @@ module PlaceOS::Api # Build result hash with parent_id as key and metadata as value result = {} of String => ::PlaceOS::Model::Metadata::Interface? + parent_ids = parent_ids.select { |id| id == user_token.id || parent_in_reach?(id) } + parent_ids.each do |parent_id| metadata = ::PlaceOS::Model::Metadata.for(parent_id, metadata_name).first? result[parent_id] = metadata ? metadata.interface : nil diff --git a/src/placeos-rest-api/controllers/modules.cr b/src/placeos-rest-api/controllers/modules.cr index 677bee16..ee21c1e8 100644 --- a/src/placeos-rest-api/controllers/modules.cr +++ b/src/placeos-rest-api/controllers/modules.cr @@ -39,7 +39,9 @@ module PlaceOS::Api def find_current_module(id : String) Log.context.set(module_id: id) # Find will raise a 404 (not found) if there is an error - @current_module = ::PlaceOS::Model::Module.find!(id) + mod = ::PlaceOS::Model::Module.find!(id) + ensure_reach!(mod) + @current_module = mod end getter! current_module : ::PlaceOS::Model::Module @@ -111,7 +113,9 @@ module PlaceOS::Api org_zone = support_org_zone_id if control_system_id - zones = ::PlaceOS::Model::ControlSystem.find!(control_system_id).zones + system = ::PlaceOS::Model::ControlSystem.find!(control_system_id) + ensure_reach!(system) + zones = system.zones # "support" subsystem: Read on the system's zones. return if support_subsystem_grants?(zones, ::PlaceOS::Model::Permissions::Read) # legacy org_zone path: the system must include the org_zone and the @@ -182,6 +186,7 @@ module PlaceOS::Api # if a system id is present we query the database directly if control_system_id cs = ::PlaceOS::Model::ControlSystem.find!(control_system_id) + ensure_reach!(cs) # Include subset of association data with results results = ::PlaceOS::Model::Module.find_all(cs.modules).compact_map do |mod| next if (driver = mod.driver).nil? @@ -197,10 +202,8 @@ module PlaceOS::Api end # PG full-text search (PPT-2644) - query = ::PlaceOS::Model::Module.all + query = scope_organisations(::PlaceOS::Model::Module.all) - # TODO:: we can remove this once there is a tenant_id field on modules - # which will make this much simpler to filter if scope_zones = module_scope_zones # we only want to show modules in use by systems within these zones no_logic = true @@ -380,6 +383,8 @@ module PlaceOS::Api mod : ::PlaceOS::Model::Module, @[AC::Param::Info(description: "add the new module to this control system", example: "sys-1234")] system_id : String? = nil, + @[AC::Param::Info(description: "the organisation that owns a module not bound to a system (cluster admins only)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, ) : ::PlaceOS::Model::Module if system_id # only logic modules have a parent system, and they're added to it by an `after_create` callback @@ -391,6 +396,13 @@ module PlaceOS::Api end can_modify?(mod) + mod.organisation_id = if cs_id = mod.control_system_id + system = ::PlaceOS::Model::ControlSystem.find!(cs_id) + ensure_reach!(system) + system.organisation_id + else + organisation_for_new_row(organisation_id) + end raise Error::ModelValidation.new(mod.errors) unless mod.save mod end @@ -399,6 +411,9 @@ module PlaceOS::Api # adding it to the system doesn't leave an orphaned module behind. private def create_in_system(mod : ::PlaceOS::Model::Module, system_id : String) : ::PlaceOS::Model::Module sys = ::PlaceOS::Model::ControlSystem.find!(system_id) + # a new module belongs to the organisation of the system it's created in + ensure_reach!(sys) + mod.organisation_id = sys.organisation_id # the module isn't in any system yet, so the target system's zones are the only ones that apply. # Adding to the system requires the same access as `PUT /systems/:sys_id/module/:module_id` diff --git a/src/placeos-rest-api/controllers/oauth_applications.cr b/src/placeos-rest-api/controllers/oauth_applications.cr index 8e41ecdc..9cca240e 100644 --- a/src/placeos-rest-api/controllers/oauth_applications.cr +++ b/src/placeos-rest-api/controllers/oauth_applications.cr @@ -20,7 +20,9 @@ module PlaceOS::Api def find_current_app(id : String) Log.context.set(application_id: id) # Find will raise a 404 (not found) if there is an error - @current_app = ::PlaceOS::Model::DoorkeeperApplication.find!(id.to_i) + app = ::PlaceOS::Model::DoorkeeperApplication.find!(id.to_i) + ensure_authority_reach!(app.owner_id, "application") + @current_app = app end getter! current_app : ::PlaceOS::Model::DoorkeeperApplication @@ -38,7 +40,9 @@ module PlaceOS::Api if user_support? # admin/support: optional authority_id filter, no subsystem gating. + query = scope_authorities(query, "owner_id") if authority = authority_id + ensure_authority_reach!(authority, "domain") query = query.where(owner_id: authority) end else @@ -87,6 +91,7 @@ module PlaceOS::Api # add a new user interface application @[AC::Route::POST("/", body: :app, status_code: HTTP::Status::CREATED)] def create(app : ::PlaceOS::Model::DoorkeeperApplication) : ::PlaceOS::Model::DoorkeeperApplication + ensure_authority_reach!(app.owner_id, "domain") raise Error::ModelValidation.new(app.errors) unless app.save app end diff --git a/src/placeos-rest-api/controllers/organisations.cr b/src/placeos-rest-api/controllers/organisations.cr new file mode 100644 index 00000000..2a90b10c --- /dev/null +++ b/src/placeos-rest-api/controllers/organisations.cr @@ -0,0 +1,171 @@ +require "placeos-models/organisation" +require "placeos-models/partner" + +require "./application" + +module PlaceOS::Api + # Organisations: the customers that own domains and estate (PPT-526) + class Organisations < Application + base "/api/engine/v2/organisations/" + + # Scopes + ############################################################################################### + + before_action :can_read, only: [:index, :show, :current] + before_action :can_write, only: [:create, :update, :destroy, :claim] + + before_action :check_support, only: [:index, :show] + before_action :check_cluster_admin, only: [:create, :update, :destroy, :claim] + + ############################################################################################### + + @[AC::Route::Filter(:before_action, except: [:index, :create, :current])] + def find_current_organisation(id : UUID) + Log.context.set(organisation_id: id.to_s) + organisation = ::PlaceOS::Model::Organisation.find!(id) + ensure_reach!(organisation.id, "organisation") + @current_organisation_row = organisation + end + + getter! current_organisation_row : ::PlaceOS::Model::Organisation + + ############################################################################################### + + # What the caller can reach: the level, their own organisation and partner, + # and the organisations in reach. Backoffice reads this once at login. + record CurrentReach, + reach : String, + enforcing : Bool, + organisation : ::PlaceOS::Model::Organisation?, + partner : ::PlaceOS::Model::Partner?, + organisations : Array(::PlaceOS::Model::Organisation)? do + include JSON::Serializable + end + + @[AC::Route::GET("/current")] + def current : CurrentReach + scope = tenancy + organisations = scope.organisation_ids.try do |ids| + ids.empty? ? [] of ::PlaceOS::Model::Organisation : ::PlaceOS::Model::Organisation.find_all(ids.to_a).to_a + end + CurrentReach.new( + reach: scope.reach.to_s.downcase, + enforcing: Utils::Tenancy.enforce?, + organisation: scope.organisation, + partner: scope.partner, + organisations: organisations, + ) + end + + # list the organisations in reach + @[AC::Route::GET("/")] + def index( + @[AC::Param::Info(description: "only organisations under this partner", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + partner_id : UUID? = nil, + ) : Array(::PlaceOS::Model::Organisation) + query = ::PlaceOS::Model::Organisation.all + query = query.where(partner_id: partner_id) if partner_id + ids = tenancy.organisation_ids + if ids + list = ids.to_a.map(&.to_s) + query = list.empty? ? query.where("1 = ?", 0) : query.where("id = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[])", list) + end + paginate_search(query, ::PlaceOS::Model::Organisation.table_name) + end + + @[AC::Route::GET("/:id")] + def show : ::PlaceOS::Model::Organisation + current_organisation_row + end + + # `payer` and `partner_staff` are not mass-assignable, so they travel as + # parameters + @[AC::Route::POST("/", body: :organisation, status_code: HTTP::Status::CREATED)] + def create( + organisation : ::PlaceOS::Model::Organisation, + @[AC::Param::Info(description: "who is invoiced: partner or organisation", example: "partner")] + payer : String? = nil, + @[AC::Param::Info(description: "true for the partner's own staff organisation", example: "false")] + partner_staff : Bool? = nil, + ) : ::PlaceOS::Model::Organisation + organisation.payer = payer if payer + organisation.partner_staff = partner_staff unless partner_staff.nil? + raise Error::ModelValidation.new(organisation.errors) unless organisation.save + organisation + end + + @[AC::Route::PATCH("/:id", body: :organisation)] + @[AC::Route::PUT("/:id", body: :organisation)] + def update( + organisation : ::PlaceOS::Model::Organisation, + @[AC::Param::Info(description: "who is invoiced: partner or organisation", example: "partner")] + payer : String? = nil, + @[AC::Param::Info(description: "true for the partner's own staff organisation", example: "false")] + partner_staff : Bool? = nil, + ) : ::PlaceOS::Model::Organisation + current = current_organisation_row + current.assign_attributes(organisation) + current.payer = payer if payer + current.partner_staff = partner_staff unless partner_staff.nil? + raise Error::ModelValidation.new(current.errors) unless current.save + current + end + + # Deletes are RESTRICTed by the database while anything is owned + @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] + def destroy : Nil + current_organisation_row.destroy + end + + record ClaimBody, zone_ids : Array(String) do + include JSON::Serializable + end + + record ClaimResult, zones : Int64, systems : Int64, modules : Int64, triggers : Int64 do + include JSON::Serializable + end + + # Assigns unowned zone trees to the organisation: the zones named, their + # descendants, the systems in those zones and the modules of those + # systems. Rows already owned by another organisation are left alone. + @[AC::Route::POST("/:id/claim", body: :body)] + def claim(body : ClaimBody) : ClaimResult + organisation_id = current_organisation_row.id.as(UUID).to_s + roots = body.zone_ids.uniq + return ClaimResult.new(0, 0, 0, 0) if roots.empty? + + PgORM::Database.connection do |db| + zones = db.exec(<<-SQL, args: [roots, organisation_id]).rows_affected + WITH RECURSIVE tree AS ( + SELECT id FROM zone WHERE id = ANY($1::text[]) + UNION + SELECT z.id FROM zone z INNER JOIN tree t ON z.parent_id = t.id + ) + UPDATE zone SET organisation_id = $2::uuid + WHERE id IN (SELECT id FROM tree) AND organisation_id IS NULL + SQL + systems = db.exec(<<-SQL, args: [organisation_id]).rows_affected + UPDATE sys SET organisation_id = $1::uuid + WHERE organisation_id IS NULL + AND EXISTS (SELECT 1 FROM zone z WHERE z.id = ANY(sys.zones) AND z.organisation_id = $1::uuid) + AND NOT EXISTS (SELECT 1 FROM zone z WHERE z.id = ANY(sys.zones) AND z.organisation_id IS NOT NULL AND z.organisation_id <> $1::uuid) + SQL + modules = db.exec(<<-SQL, args: [organisation_id]).rows_affected + UPDATE mod SET organisation_id = $1::uuid + WHERE organisation_id IS NULL + AND ( + control_system_id IN (SELECT id FROM sys WHERE organisation_id = $1::uuid) + OR EXISTS (SELECT 1 FROM sys s WHERE mod.id = ANY(s.modules) AND s.organisation_id = $1::uuid) + ) + AND NOT EXISTS (SELECT 1 FROM sys s WHERE mod.id = ANY(s.modules) AND s.organisation_id IS NOT NULL AND s.organisation_id <> $1::uuid) + SQL + triggers = db.exec(<<-SQL, args: [organisation_id]).rows_affected + UPDATE trigger SET organisation_id = $1::uuid + WHERE organisation_id IS NULL + AND control_system_id IN (SELECT id FROM sys WHERE organisation_id = $1::uuid) + SQL + ClaimResult.new(zones, systems, modules, triggers) + end + end + end +end diff --git a/src/placeos-rest-api/controllers/partners.cr b/src/placeos-rest-api/controllers/partners.cr new file mode 100644 index 00000000..8c4cce43 --- /dev/null +++ b/src/placeos-rest-api/controllers/partners.cr @@ -0,0 +1,74 @@ +require "placeos-models/partner" + +require "./application" + +module PlaceOS::Api + # Partners: integrators that bring in and manage organisations, and the + # management partner that is PlaceOS itself (PPT-526) + class Partners < Application + base "/api/engine/v2/partners/" + + # Scopes + ############################################################################################### + + before_action :can_read, only: [:index, :show] + before_action :can_write, only: [:create, :update, :destroy] + + before_action :check_support, only: [:index, :show] + before_action :check_cluster_admin, only: [:create, :update, :destroy] + + ############################################################################################### + + @[AC::Route::Filter(:before_action, except: [:index, :create])] + def find_current_partner(id : UUID) + Log.context.set(partner_id: id.to_s) + partner = ::PlaceOS::Model::Partner.find!(id) + unless tenancy.cluster? || tenancy.partner.try(&.id) == partner.id + log_would_refuse("partner outside reach") + raise Error::NotFound.new("partner not found") if Utils::Tenancy.enforce? + end + @current_partner_row = partner + end + + getter! current_partner_row : ::PlaceOS::Model::Partner + + ############################################################################################### + + # cluster admins list every partner; everyone else sees their own + @[AC::Route::GET("/")] + def index : Array(::PlaceOS::Model::Partner) + query = ::PlaceOS::Model::Partner.all + unless tenancy.cluster? + own = tenancy.partner.try(&.id) + query = own ? query.where(id: own) : query.where("1 = ?", 0) + end + paginate_search(query, ::PlaceOS::Model::Partner.table_name) + end + + @[AC::Route::GET("/:id")] + def show : ::PlaceOS::Model::Partner + current_partner_row + end + + @[AC::Route::POST("/", body: :partner, status_code: HTTP::Status::CREATED)] + def create(partner : ::PlaceOS::Model::Partner) : ::PlaceOS::Model::Partner + raise Error::ModelValidation.new(partner.errors) unless partner.save + partner + end + + @[AC::Route::PATCH("/:id", body: :partner)] + @[AC::Route::PUT("/:id", body: :partner)] + def update(partner : ::PlaceOS::Model::Partner) : ::PlaceOS::Model::Partner + current = current_partner_row + current.assign_attributes(partner) + raise Error::ModelValidation.new(current.errors) unless current.save + current + end + + # Deletes are RESTRICTed by the database while organisations remain + @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] + def destroy : Nil + current_partner_row.destroy + end + end +end diff --git a/src/placeos-rest-api/controllers/repositories.cr b/src/placeos-rest-api/controllers/repositories.cr index 62f723e2..86bac348 100644 --- a/src/placeos-rest-api/controllers/repositories.cr +++ b/src/placeos-rest-api/controllers/repositories.cr @@ -16,6 +16,8 @@ module PlaceOS::Api before_action :check_admin, except: [:index, :show] before_action :check_support, only: [:index, :show] + # repositories are shared by every organisation; only cluster admins change them + before_action :check_cluster_admin, only: [:create, :update, :destroy, :remove, :pull] ############################################################################################### diff --git a/src/placeos-rest-api/controllers/schema.cr b/src/placeos-rest-api/controllers/schema.cr index 42b3b24b..f8fb2ffc 100644 --- a/src/placeos-rest-api/controllers/schema.cr +++ b/src/placeos-rest-api/controllers/schema.cr @@ -11,6 +11,7 @@ module PlaceOS::Api before_action :can_read, only: [:index, :show] before_action :check_admin, except: [:index, :show] + before_action :check_cluster_admin, except: [:index, :show] before_action :check_support, only: [:index, :show] ############################################################################################### diff --git a/src/placeos-rest-api/controllers/settings.cr b/src/placeos-rest-api/controllers/settings.cr index e14f96af..cd75b77a 100644 --- a/src/placeos-rest-api/controllers/settings.cr +++ b/src/placeos-rest-api/controllers/settings.cr @@ -32,6 +32,7 @@ module PlaceOS::Api ############################################################################################### def can_view?(parent_id) + ensure_parent_reach!(parent_id) return if user_support? # "support" subsystem: Read on the parent's zones. return if support_subsystem_grants?(support_zones_for_parent(parent_id), ::PlaceOS::Model::Permissions::Read) @@ -39,9 +40,12 @@ module PlaceOS::Api end def can_modify?(setting) + parent_id = setting.parent_id.as(String) + ensure_parent_reach!(parent_id) + # driver settings are shared by every organisation + check_cluster_admin if parent_id.starts_with?(::PlaceOS::Model::Driver.table_name) return if user_admin? raise Error::Forbidden.new("can only modify unencrypted settings") unless setting.encryption_level.none? - parent_id = setting.parent_id.as(String) # "support" subsystem: the verb's bit on the parent's zones. A # parent with no derivable zones (e.g. a driver) stays admin-only. return if support_subsystem_grants?(support_zones_for_parent(parent_id), verb_permission) @@ -102,6 +106,8 @@ module PlaceOS::Api parent_settings else raise Error::Forbidden.new unless user_support? + # the unscoped list spans every organisation + check_cluster_admin # PG full-text search (PPT-2644): `q` matches the settings keys (and # id) — the settings body itself is deliberately not searchable. diff --git a/src/placeos-rest-api/controllers/system-triggers.cr b/src/placeos-rest-api/controllers/system-triggers.cr index 40b0fdf8..b82f94ef 100644 --- a/src/placeos-rest-api/controllers/system-triggers.cr +++ b/src/placeos-rest-api/controllers/system-triggers.cr @@ -22,14 +22,18 @@ module PlaceOS::Api # the legacy org_zone path bypass as usual). @[AC::Route::Filter(:before_action, only: [:index, :show])] def check_trigger_read_permissions(sys_id : String) - zones = ::PlaceOS::Model::ControlSystem.find!(sys_id).zones + system = ::PlaceOS::Model::ControlSystem.find!(sys_id) + ensure_reach!(system) + zones = system.zones ensure_support_access!(zones, ::PlaceOS::Model::Permissions::Read) @secret_visible = secret_visible_on?(zones) end @[AC::Route::Filter(:before_action, only: [:create, :update, :destroy])] def check_trigger_write_permissions(sys_id : String) - zones = ::PlaceOS::Model::ControlSystem.find!(sys_id).zones + system = ::PlaceOS::Model::ControlSystem.find!(sys_id) + ensure_reach!(system) + zones = system.zones ensure_support_access!(zones, verb_permission) @secret_visible = secret_visible_on?(zones) end diff --git a/src/placeos-rest-api/controllers/systems.cr b/src/placeos-rest-api/controllers/systems.cr index 66879540..183e97ed 100644 --- a/src/placeos-rest-api/controllers/systems.cr +++ b/src/placeos-rest-api/controllers/systems.cr @@ -38,15 +38,24 @@ module PlaceOS::Api ) Log.context.set(control_system_id: sys_id) # Find will raise a 404 (not found) if there is an error - if sys_id.includes?('@') - systems = find_by_email([sys_id]) - if systems.size > 0 - @current_control_system = systems.first - else - raise Error::NotFound.new("no system with email: #{sys_id}") - end - else - @current_control_system = ::PlaceOS::Model::ControlSystem.find!(sys_id) + system = if sys_id.includes?('@') + systems = find_by_email([sys_id]) + raise Error::NotFound.new("no system with email: #{sys_id}") if systems.empty? + systems.first + else + ::PlaceOS::Model::ControlSystem.find!(sys_id) + end + ensure_reach!(system) + @current_control_system = system + end + + # The lazily gated routes (execute, functions, state, state_lookup, types) + # take the system id without loading the row; a system that exists must + # be in reach. + @[AC::Route::Filter(:before_action, only: [:execute, :functions, :state, :state_lookup, :types, :metadata])] + def check_lazy_reach(sys_id : String) + if system = ::PlaceOS::Model::ControlSystem.find?(sys_id) + ensure_reach!(system) end end @@ -239,7 +248,7 @@ module PlaceOS::Api signage : Bool? = nil, ) : Array(::PlaceOS::Model::ControlSystem) # PG full-text search (PPT-2644) - query = ::PlaceOS::Model::ControlSystem.all + query = scope_organisations(::PlaceOS::Model::ControlSystem.all) # `zone_id` keeps its original AND semantics — a system must # contain *every* listed zone. The intended use is intersection @@ -344,7 +353,7 @@ module PlaceOS::Api @[AC::Param::Info(name: "in", description: "comma seperated list of emails", example: "room1@org.com,room2@org.com")] emails : Array(String), ) : Array(::PlaceOS::Model::ControlSystem) - systems = ::PlaceOS::Model::ControlSystem.where(email: emails.map(&.strip.downcase)).to_a + systems = scope_organisations(::PlaceOS::Model::ControlSystem.where(email: emails.map(&.strip.downcase))).to_a set_collection_headers(systems.size, ::PlaceOS::Model::ControlSystem.table_name) systems end @@ -405,14 +414,23 @@ module PlaceOS::Api current = current_control_system current.assign_attributes(updated) current.version = version + 1 + if updated.zones_assigned? + owner = organisation_for_zones(current.zones) + if owner && current.organisation_id && owner != current.organisation_id + raise Error::ModelValidation.new([Utils::Tenancy::Failure.new(:zones, "zones belong to another organisation")], "zones belong to another organisation") + end + current.organisation_id ||= owner + end raise Error::ModelValidation.new(current.errors) unless current.save current end - # adds a new system + # adds a new system. The system belongs to its zones' organisation, or + # the caller's when the zones are unowned. @[AC::Route::POST("/", status_code: HTTP::Status::CREATED)] def create : ::PlaceOS::Model::ControlSystem sys = control_system_update + sys.organisation_id = organisation_for_zones(sys.zones) raise Error::ModelValidation.new(sys.errors) unless sys.save sys end @@ -465,7 +483,14 @@ module PlaceOS::Api def add_module( module_id : String, ) : ::PlaceOS::Model::ControlSystem - raise Error::NotFound.new unless ::PlaceOS::Model::Module.exists?(module_id) + mod = ::PlaceOS::Model::Module.find?(module_id) + raise Error::NotFound.new unless mod + ensure_reach!(mod) + # a cluster admin attaching an unowned module adopts it into the system's organisation + if mod.organisation_id.nil? && (owner = current_control_system.organisation_id) + mod.organisation_id = owner + mod.save! + end module_present = current_control_system.modules.includes?(module_id) || ::PlaceOS::Model::ControlSystem.add_module(current_control_system.id.as(String), module_id) raise "Failed to add ControlSystem Module" unless module_present @@ -665,6 +690,7 @@ module PlaceOS::Api ws: ws, request_id: request_id, user: user_token, + organisation_ids: tenancy.organisation_ids, ) end diff --git a/src/placeos-rest-api/controllers/tenant_consent.cr b/src/placeos-rest-api/controllers/tenant_consent.cr index 2c56fac0..164955e0 100644 --- a/src/placeos-rest-api/controllers/tenant_consent.cr +++ b/src/placeos-rest-api/controllers/tenant_consent.cr @@ -35,6 +35,7 @@ module PlaceOS::Api @[AC::Route::GET("/:id")] def index(id : String) : NamedTuple(url: String) authority = ::PlaceOS::Model::Authority.find!(id) + ensure_reach!(authority) update_app_redirect_uri callback_url = URI.encode_www_form(redirect_url) # Not the authority id. `state` comes back from Microsoft through the diff --git a/src/placeos-rest-api/controllers/triggers.cr b/src/placeos-rest-api/controllers/triggers.cr index d6f61812..32e42859 100644 --- a/src/placeos-rest-api/controllers/triggers.cr +++ b/src/placeos-rest-api/controllers/triggers.cr @@ -22,7 +22,17 @@ module PlaceOS::Api def find_current_trigger(id : String) Log.context.set(trigger_id: id) # Find will raise a 404 (not found) if there is an error - @current_trigger = ::PlaceOS::Model::Trigger.find!(id) + trigger = ::PlaceOS::Model::Trigger.find!(id) + # a trigger bound to a system follows that system; a definition with + # no system is a template any organisation may instantiate + ensure_reach!(trigger) if trigger.control_system_id + @current_trigger = trigger + end + + # Templates are cluster-managed + @[AC::Route::Filter(:before_action, only: [:update, :destroy])] + def check_template_write + check_cluster_admin if current_trigger.control_system_id.nil? end getter! current_trigger : ::PlaceOS::Model::Trigger @@ -33,7 +43,16 @@ module PlaceOS::Api @[AC::Route::GET("/")] def index : Array(::PlaceOS::Model::Trigger) # PG full-text search (PPT-2644) - paginate_search(::PlaceOS::Model::Trigger.all, ::PlaceOS::Model::Trigger.table_name) + query = ::PlaceOS::Model::Trigger.all + if ids = tenancy.organisation_ids + list = ids.to_a.map(&.to_s) + query = if list.empty? + query.where("control_system_id IS NULL", [] of String) + else + query.where("(control_system_id IS NULL OR organisation_id = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[]))", list) + end + end + paginate_search(query, ::PlaceOS::Model::Trigger.table_name) end # update so we can provide instance details @@ -66,6 +85,13 @@ module PlaceOS::Api # adds a new trigger @[AC::Route::POST("/", body: :trig, status_code: HTTP::Status::CREATED)] def create(trig : ::PlaceOS::Model::Trigger) : ::PlaceOS::Model::Trigger + if cs_id = trig.control_system_id + system = ::PlaceOS::Model::ControlSystem.find!(cs_id) + ensure_reach!(system) + trig.organisation_id = system.organisation_id + else + check_cluster_admin + end raise Error::ModelValidation.new(trig.errors) unless trig.save trig end diff --git a/src/placeos-rest-api/controllers/users.cr b/src/placeos-rest-api/controllers/users.cr index b9aad311..b66b46ef 100644 --- a/src/placeos-rest-api/controllers/users.cr +++ b/src/placeos-rest-api/controllers/users.cr @@ -65,9 +65,11 @@ module PlaceOS::Api raise PgORM::Error::RecordNotFound.new }.tap do |found| # The `:id` lookup above is not authority scoped — only admins may - # resolve users belonging to other authorities. 404 (not 403) so - # foreign ids are indistinguishable from unknown ones. + # resolve users belonging to other authorities, and only within their + # reach. 404 (not 403) so foreign ids are indistinguishable from + # unknown ones. raise PgORM::Error::RecordNotFound.new unless user_admin? || found.authority_id == authority + ensure_authority_reach!(found.authority_id, "user") unless found.authority_id == authority Log.context.set(user_id: found.id) @user = found end @@ -162,7 +164,11 @@ module PlaceOS::Api # regular users can only see their own domain query = query.where(authority_id: current_user.authority_id.as(String)) elsif authority = authority_id + ensure_authority_reach!(authority, "domain") query = query.where(authority_id: authority) + else + # admins see every domain within reach + query = scope_authorities(query) end results = paginate_search(query, ::PlaceOS::Model::User.table_name) @@ -207,8 +213,9 @@ module PlaceOS::Api # only be set by admins — support-subsystem creators would otherwise # be able to mint sys-admins. new_user.assign_admin_attributes_from_json(body) - # allow sys-admins to create users on other domains + # allow sys-admins to create users on other domains within reach new_user.authority ||= current_authority.as(::PlaceOS::Model::Authority) + ensure_authority_reach!(new_user.authority_id, "domain") else # non-admins always create users in their own authority new_user.authority = current_authority.as(::PlaceOS::Model::Authority) diff --git a/src/placeos-rest-api/controllers/zones.cr b/src/placeos-rest-api/controllers/zones.cr index 6a0f71a4..ba6fd411 100644 --- a/src/placeos-rest-api/controllers/zones.cr +++ b/src/placeos-rest-api/controllers/zones.cr @@ -37,7 +37,9 @@ module PlaceOS::Api def current_zone(id : String) Log.context.set(zone_id: id) # Find will raise a 404 (not found) if there is an error - @current_zone = ::PlaceOS::Model::Zone.find!(id) + zone = ::PlaceOS::Model::Zone.find!(id) + ensure_reach!(zone) + @current_zone = zone end getter! current_zone : ::PlaceOS::Model::Zone @@ -179,7 +181,7 @@ module PlaceOS::Api # the same for `?parent_id=` as for no param at all parent_id = nil if parent_id.try(&.empty?) - query = ::PlaceOS::Model::Zone.all + query = scope_organisations(::PlaceOS::Model::Zone.all) if group_id && descendants query = query.where("id IN (#{group_descendants_sql})", group_id.to_s) @@ -269,8 +271,14 @@ module PlaceOS::Api # returns unique zone tags @[AC::Route::GET("/tags")] def tags : Array(String) + ids = tenancy.organisation_ids + return [] of String if ids && ids.empty? unique_tags = PgORM::Database.connection do |db| - db.query_one "select string_agg(distinct tag, ', ' order by tag) as types from ( select unnest(tags) as tag from zone ) as unnested", &.read(String) + if ids + db.query_one "select string_agg(distinct tag, ', ' order by tag) as types from ( select unnest(tags) as tag from zone where organisation_id = ANY($1::uuid[]) ) as unnested", args: [ids.to_a.map(&.to_s)], &.read(String) + else + db.query_one "select string_agg(distinct tag, ', ' order by tag) as types from ( select unnest(tags) as tag from zone ) as unnested", &.read(String) + end end unique_tags.split(',') rescue DB::ColumnTypeMismatchError @@ -296,14 +304,31 @@ module PlaceOS::Api zone = zone_update current = current_zone current.assign_attributes(zone) + if (parent_id = current.parent_id.presence) && current.parent_id_changed? + parent = ::PlaceOS::Model::Zone.find!(parent_id) + ensure_reach!(parent) + raise Error::ModelValidation.new([Utils::Tenancy::Failure.new(:parent_id, "parent belongs to another organisation")], "parent belongs to another organisation") unless parent.organisation_id == current.organisation_id + end raise Error::ModelValidation.new(current.errors) unless current.save current end - # add a new zone + # add a new zone. A child zone belongs to its parent's organisation; a + # root zone belongs to the caller's, or to the organisation a cluster + # admin names. @[AC::Route::POST("/", status_code: HTTP::Status::CREATED)] - def create : ::PlaceOS::Model::Zone + def create( + @[AC::Param::Info(description: "the organisation that owns a new root zone (cluster admins only)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : ::PlaceOS::Model::Zone zone = zone_update + zone.organisation_id = if parent_id = zone.parent_id.presence + parent = ::PlaceOS::Model::Zone.find!(parent_id) + ensure_reach!(parent) + parent.organisation_id + else + organisation_for_new_row(organisation_id) + end raise Error::ModelValidation.new(zone.errors) unless zone.save zone end @@ -323,6 +348,7 @@ module PlaceOS::Api @[AC::Param::Info(description: "only return the metadata key we are interested in", example: "workplace-config")] name : String? = nil, ) : Hash(String, ::PlaceOS::Model::Metadata::Interface) + ensure_reach!(::PlaceOS::Model::Zone.find!(id)) ::PlaceOS::Model::Metadata.build_metadata(id, name) end diff --git a/src/placeos-rest-api/utilities/tenancy.cr b/src/placeos-rest-api/utilities/tenancy.cr new file mode 100644 index 00000000..21bbe510 --- /dev/null +++ b/src/placeos-rest-api/utilities/tenancy.cr @@ -0,0 +1,269 @@ +require "uuid" +require "placeos-models/authority" +require "placeos-models/organisation" +require "placeos-models/partner" +require "placeos-models/grant" + +require "../../constants" + +module PlaceOS::Api + # Resolves, once per request, which organisations the caller may reach, and + # exposes the scope filter and reach checks the controllers apply. + # + # Reach is structural first and granted second: + # - cluster: an admin or support user whose domain's organisation belongs to + # the management partner. Sees every organisation, as before PPT-526. + # - partner: an admin or support user on a partner's staff organisation + # (`organisations.partner_staff`). Sees every organisation under that partner. + # - organisation: everyone else sees their own organisation only. + # Live grants widen the organisation set without changing the level. + # + # Rows with no organisation (unowned) are visible to cluster reach only. + # A caller whose domain has no organisation reaches nothing. + # + # `Tenancy.enforce?` (from `PLACE_TENANCY_ENFORCE`) switches between refusing + # and logging what would have been refused; the resolver runs either way. + module Utils::Tenancy + Log = ::Log.for("tenancy") + + class_property? enforce : Bool = PLACE_TENANCY_ENFORCE + + enum Reach + Cluster + Partner + Organisation + end + + # Shape `Error::ModelValidation` reads failures from + record Failure, field : Symbol, message : String + + # The resolved reach of the current request. `organisation_ids` is nil for + # cluster reach (no filter) and otherwise the exact set, possibly empty. + record Scope, + reach : Reach, + organisation_ids : Set(UUID)?, + organisation : ::PlaceOS::Model::Organisation?, + partner : ::PlaceOS::Model::Partner? do + def cluster? : Bool + reach.cluster? + end + + def includes?(organisation_id : UUID?) : Bool + return true if cluster? + return false if organisation_id.nil? + organisation_ids.as(Set(UUID)).includes?(organisation_id) + end + + def organisation_id : UUID? + organisation.try(&.id) + end + end + + getter current_organisation : ::PlaceOS::Model::Organisation? { current_authority.try(&.organisation) } + getter current_partner : ::PlaceOS::Model::Partner? { current_organisation.try(&.partner) } + + # The caller's reach as it will be once enforcement is on. Controllers + # never read this directly for gating; see `tenancy`. + getter resolved_tenancy : Scope { resolve_tenancy } + + # The scope controllers apply. With enforcement off this is always cluster + # reach, so behaviour matches the release before PPT-526. + getter tenancy : Scope do + if Utils::Tenancy.enforce? + resolved_tenancy + else + Scope.new(Reach::Cluster, nil, current_organisation, current_partner) + end + end + + protected def resolve_tenancy : Scope + organisation = current_organisation + partner = current_partner + privileged = user_support? + + if organisation.nil? + Log.warn { {message: "domain has no organisation, caller reaches nothing", authority: current_authority.try(&.id), user_id: user_token.id} } + return Scope.new(Reach::Organisation, Set(UUID).new, nil, nil) + end + + organisation_id = organisation.id.as(UUID) + + if privileged && partner && partner.management + return Scope.new(Reach::Cluster, nil, organisation, partner) + end + + reach, ids = if privileged && partner && organisation.partner_staff + {Reach::Partner, organisation.partner_organisations.to_a.compact_map(&.id).to_set} + else + {Reach::Organisation, Set{organisation_id}} + end + + ids.concat(granted_organisation_ids) + Scope.new(reach, ids, organisation, partner) + end + + # Organisations the caller reaches through live grants that carry Read. + protected def granted_organisation_ids : Set(UUID) + ids = Set(UUID).new + return ids if user_token.guest_scope? + user_id = user_token.id + + ::PlaceOS::Model::Grant.for_user(user_id).each do |grant| + next unless grant.permission_flags.read? || grant.permission_flags.manage? + scope_id = grant.scope_id + case grant.scope_type + when ::PlaceOS::Model::Grant::SCOPE_ORGANISATION + UUID.parse?(scope_id).try { |id| ids << id } + when ::PlaceOS::Model::Grant::SCOPE_PARTNER + if partner_id = UUID.parse?(scope_id) + ::PlaceOS::Model::Organisation.where(partner_id: partner_id).each { |org| org.id.try { |id| ids << id } } + end + when ::PlaceOS::Model::Grant::SCOPE_AUTHORITY + ::PlaceOS::Model::Authority.find?(scope_id).try(&.organisation_id).try { |id| ids << id } + end + end + ids + end + + # ------------------------------------------------------------------ + # Gates + # ------------------------------------------------------------------ + + # Cluster-only routes (repositories, drivers, brokers, cluster, build jobs). + def check_cluster_admin + raise Error::Forbidden.new unless user_admin? + return if tenancy.cluster? + log_would_refuse("cluster admin required") + raise Error::Forbidden.new if Utils::Tenancy.enforce? + end + + # Raises 404 when `organisation_id` is outside the caller's reach, so a + # foreign id is indistinguishable from an unknown one. Unowned rows are in + # reach for cluster callers only. + def ensure_reach!(organisation_id : UUID?, resource : String = "resource") : Nil + return if tenancy.includes?(organisation_id) + log_would_refuse("#{resource} outside reach", organisation_id) + raise Error::NotFound.new("#{resource} not found") if Utils::Tenancy.enforce? + end + + def ensure_reach!(row : ::PlaceOS::Model::Authority | ::PlaceOS::Model::Zone | ::PlaceOS::Model::ControlSystem | ::PlaceOS::Model::Module | ::PlaceOS::Model::Trigger | ::PlaceOS::Model::Edge | ::PlaceOS::Model::Broker) : Nil + ensure_reach!(row.organisation_id, row.class.table_name) + end + + # Reach for a row owned through its domain (users, api keys, auth sources, + # OAuth applications). + def ensure_authority_reach!(authority_id : String?, resource : String = "resource") : Nil + return if tenancy.cluster? + organisation_id = authority_id.try { |id| ::PlaceOS::Model::Authority.find?(id).try(&.organisation_id) } + ensure_reach!(organisation_id, resource) + end + + # True when the caller may act on `organisation_id`; the quiet form of + # `ensure_reach!` for building filtered lists. + def in_reach?(organisation_id : UUID?) : Bool + tenancy.includes?(organisation_id) + end + + # ------------------------------------------------------------------ + # Query scoping + # ------------------------------------------------------------------ + + # Appends the reach filter to a relation on a table with an + # `organisation_id` column. No-op for cluster reach. + def scope_organisations(query, column : String = "organisation_id") + ids = tenancy.organisation_ids + return query if ids.nil? + if ids.empty? + query.where("1 = ?", 0) + else + list = ids.to_a.map(&.to_s) + query.where("#{column} = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[])", list) + end + end + + # As above for tables owned through their domain (`authority_id`). + def scope_authorities(query, column : String = "authority_id") + ids = tenancy.organisation_ids + return query if ids.nil? + if ids.empty? + query.where("1 = ?", 0) + else + list = ids.to_a.map(&.to_s) + query.where("#{column} IN (SELECT id FROM authority WHERE organisation_id = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[]))", list) + end + end + + # Domain ids in reach, for routes that take an `authority_id` parameter. + def reachable_authority_ids : Array(String)? + ids = tenancy.organisation_ids + return if ids.nil? + return [] of String if ids.empty? + list = ids.to_a.map(&.to_s) + ::PlaceOS::Model::Authority + .where("organisation_id = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[])", list) + .to_a.compact_map(&.id) + end + + # The single organisation implied by a set of zone ids: every zone must be + # in reach and owned by the same organisation. Falls back to the caller's + # own organisation when the zones are unowned or there are none. + def organisation_for_zones(zone_ids : Array(String)) : UUID? + owners = Set(UUID).new + zone_ids.uniq.each do |zone_id| + zone = ::PlaceOS::Model::Zone.find!(zone_id) + ensure_reach!(zone) + zone.organisation_id.try { |id| owners << id } + end + raise Error::ModelValidation.new([Failure.new(:zones, "zones belong to more than one organisation")], "zones belong to more than one organisation") if owners.size > 1 + owners.first? || tenancy.organisation_id + end + + # Reach check for a settings/metadata parent id (zone-, sys-, mod-, user- + # or driver- prefixed). Drivers are global, so a driver parent is always + # in reach for reads. + def ensure_parent_reach!(parent_id : String) : Nil + case parent_id + when .starts_with?("zone-") then ensure_reach!(::PlaceOS::Model::Zone.find!(parent_id)) + when .starts_with?("sys-") then ensure_reach!(::PlaceOS::Model::ControlSystem.find!(parent_id)) + when .starts_with?("mod-") then ensure_reach!(::PlaceOS::Model::Module.find!(parent_id)) + when .starts_with?("user-") then ensure_authority_reach!(::PlaceOS::Model::User.find!(parent_id).authority_id, "user") + when .starts_with?("driver-") then nil + else ensure_reach!(nil, "parent") + end + end + + # Quiet form of `ensure_parent_reach!` for filtering id lists. + def parent_in_reach?(parent_id : String) : Bool + return true if tenancy.cluster? || !Utils::Tenancy.enforce? + ensure_parent_reach!(parent_id) + true + rescue Error::NotFound | PgORM::Error::RecordNotFound + false + end + + # The organisation a newly created estate row belongs to: the caller's own, + # or, for cluster callers, an explicit choice. + def organisation_for_new_row(requested : UUID? = nil) : UUID? + if requested + raise Error::Forbidden.new("organisation outside reach") unless in_reach?(requested) + return requested + end + tenancy.organisation_id + end + + protected def log_would_refuse(reason : String, organisation_id : UUID? = nil) + scope = resolved_tenancy + Log.warn do + { + message: Utils::Tenancy.enforce? ? "tenancy refused" : "tenancy would refuse", + reason: reason, + reach: scope.reach.to_s, + caller_org: scope.organisation_id.try(&.to_s), + target_org: organisation_id.try(&.to_s), + user_id: user_token.id, + path: request.path, + } + end + end + end +end diff --git a/src/placeos-rest-api/websocket/manager.cr b/src/placeos-rest-api/websocket/manager.cr index 1820bf0a..07a200ec 100644 --- a/src/placeos-rest-api/websocket/manager.cr +++ b/src/placeos-rest-api/websocket/manager.cr @@ -27,13 +27,14 @@ module PlaceOS::Api::WebSocket # Creates the session and handles the cleanup # - def create_session(ws, request_id, user) + def create_session(ws, request_id, user, organisation_ids : Set(UUID)? = nil) Log.trace { {request_id: request_id, frame: "OPEN"} } session = Session.new( ws: ws, request_id: request_id, user: user, discovery: discovery, + organisation_ids: organisation_ids, ) session_lock.synchronize { sessions << session } diff --git a/src/placeos-rest-api/websocket/session.cr b/src/placeos-rest-api/websocket/session.cr index dac001a2..727284dc 100644 --- a/src/placeos-rest-api/websocket/session.cr +++ b/src/placeos-rest-api/websocket/session.cr @@ -36,11 +36,15 @@ module PlaceOS::Api::WebSocket private getter user : ::PlaceOS::Model::UserJWT + # Organisations the session may touch; nil for cluster reach (PPT-526) + private getter organisation_ids : Set(UUID)? + def initialize( @ws : HTTP::WebSocket, @request_id : String, @user : ::PlaceOS::Model::UserJWT, @discovery : Clustering::Discovery = RemoteDriver.default_discovery, + @organisation_ids : Set(UUID)? = nil, ) # Register event handlers ws.on_message do |message| @@ -73,6 +77,18 @@ module PlaceOS::Api::WebSocket # WebSocket API Handlers ############################################################################## + # True when the system is inside the session's reach. Unknown systems are + # left to the existing lookups, which answer with the module-not-found + # error the clients already handle. + protected def system_in_reach?(system_id : String) : Bool + ids = organisation_ids + return true if ids.nil? + system = ::PlaceOS::Model::ControlSystem.find?(system_id) + return true if system.nil? + owner = system.organisation_id + !owner.nil? && ids.includes?(owner) + end + protected def elevate_security(system_id : String, default : Driver::Proxy::RemoteDriver::Clearance) : Driver::Proxy::RemoteDriver::Clearance return default if default.admin? @@ -527,6 +543,12 @@ module PlaceOS::Api::WebSocket } Log.context.set(**arguments.merge({ws_request_id: @request_id})) + unless system_in_reach?(request.system_id) + Log.warn { {message: "tenancy refused", reason: "system outside reach", system_id: request.system_id, user: @user.id} } + respond error_response(request.id, :module_not_found, "could not find module: sys=#{request.system_id} mod=#{request.module_name}") + return + end + case request.command in .bind? then bind(**arguments) in .unbind? then unbind(**arguments) From 891ce6366dc977c15b905ffee5a03ac9ebea0e7b Mon Sep 17 00:00:00 2001 From: Cameron Reeves Date: Wed, 7 Oct 2026 14:55:21 +1100 Subject: [PATCH 02/50] test: PPT-2701 tenancy spec fixes and OpenAPI document A partner-less organisation tripped the non-nilable partner association; resolve the partner through its id. Regenerate OPENAPI_DOC.yml for the organisations, partners and grants routes. --- spec/controllers/tenancy_spec.cr | 4 ++-- src/placeos-rest-api/utilities/tenancy.cr | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index 407911ab..021844d5 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -21,7 +21,7 @@ module PlaceOS::Api cluster = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.placeos.admin).body) cluster["reach"].should eq "cluster" cluster["enforcing"].as_bool.should be_true - cluster["organisations"].raw.should be_nil + cluster["organisations"]?.should be_nil partner = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.ntt_staff.admin).body) partner["reach"].should eq "partner" @@ -231,7 +231,7 @@ module PlaceOS::Api tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 # an organisation admin may grant into their own organisation but not a stranger's - tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s}).status_code.should eq 201 + tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.ucla.support.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s}).status_code.should eq 201 tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.acadian.admin.id, scope_type: "organisation", scope_id: f.ucla.organisation.id.to_s}).status_code.should eq 403 end diff --git a/src/placeos-rest-api/utilities/tenancy.cr b/src/placeos-rest-api/utilities/tenancy.cr index 21bbe510..3ca6e146 100644 --- a/src/placeos-rest-api/utilities/tenancy.cr +++ b/src/placeos-rest-api/utilities/tenancy.cr @@ -60,7 +60,7 @@ module PlaceOS::Api end getter current_organisation : ::PlaceOS::Model::Organisation? { current_authority.try(&.organisation) } - getter current_partner : ::PlaceOS::Model::Partner? { current_organisation.try(&.partner) } + getter current_partner : ::PlaceOS::Model::Partner? { current_organisation.try(&.partner_id).try { |id| ::PlaceOS::Model::Partner.find?(id) } } # The caller's reach as it will be once enforcement is on. Controllers # never read this directly for gating; see `tenancy`. From 1314218bc43c38486d28ce93913c5aefc714526d Mon Sep 17 00:00:00 2001 From: Cameron Reeves Date: Wed, 7 Oct 2026 15:17:48 +1100 Subject: [PATCH 03/50] feat: PPT-2701 organisation_id filter on the estate and user lists Lets a caller with cluster or partner reach narrow domains, zones, systems, modules, triggers, edges and users to one organisation. The organisation must be within reach. --- spec/controllers/tenancy_spec.cr | 18 ++++++++++++++++++ src/placeos-rest-api/controllers/domains.cr | 8 ++++++-- src/placeos-rest-api/controllers/edges.cr | 8 ++++++-- src/placeos-rest-api/controllers/modules.cr | 4 +++- src/placeos-rest-api/controllers/systems.cr | 4 +++- src/placeos-rest-api/controllers/triggers.cr | 9 ++++++++- src/placeos-rest-api/controllers/users.cr | 6 ++++-- src/placeos-rest-api/controllers/zones.cr | 4 +++- src/placeos-rest-api/utilities/tenancy.cr | 14 ++++++++++++++ 9 files changed, 65 insertions(+), 10 deletions(-) diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index 021844d5..0f9377ec 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -81,6 +81,24 @@ module PlaceOS::Api tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.placeos.admin).status_code.should eq 200 end + it "narrows a list to one organisation on request" do + f = Spec::Tenancy.build + + narrowed = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", f.placeos.admin).body) + narrowed.should contain(f.ucla.org_zone.id) + narrowed.should_not contain(f.acadian.org_zone.id) + narrowed.should_not contain(f.unowned_zone.id) + + partner_narrowed = Spec::Tenancy.ids(tenancy_get("#{Systems.base_route}?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin).body) + partner_narrowed.should eq [f.acadian.system.id] + + tenancy_get("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", f.acadian.admin).status_code.should eq 404 + + users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?organisation_id=#{f.acadian.organisation.id}", f.placeos.admin).body) + users.should contain(f.acadian.user.id) + users.should_not contain(f.ucla.user.id) + end + it "only logs when enforcement is off" do f = Spec::Tenancy.build Utils::Tenancy.enforce = false diff --git a/src/placeos-rest-api/controllers/domains.cr b/src/placeos-rest-api/controllers/domains.cr index b757eb26..c5647e82 100644 --- a/src/placeos-rest-api/controllers/domains.cr +++ b/src/placeos-rest-api/controllers/domains.cr @@ -31,9 +31,13 @@ module PlaceOS::Api # list the domains @[AC::Route::GET("/")] - def index : Array(::PlaceOS::Model::Authority) + def index( + @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : Array(::PlaceOS::Model::Authority) # PG full-text search (PPT-2644) - paginate_search(scope_organisations(::PlaceOS::Model::Authority.all), ::PlaceOS::Model::Authority.table_name) + query = narrow_organisation(scope_organisations(::PlaceOS::Model::Authority.all), organisation_id) + paginate_search(query, ::PlaceOS::Model::Authority.table_name) end # skip authentication for the lookup diff --git a/src/placeos-rest-api/controllers/edges.cr b/src/placeos-rest-api/controllers/edges.cr index 173bbd7c..fc49cd07 100644 --- a/src/placeos-rest-api/controllers/edges.cr +++ b/src/placeos-rest-api/controllers/edges.cr @@ -73,9 +73,13 @@ module PlaceOS::Api # list the edges in the system. # an edge can be thought of as a location and each edge location can have multiple nodes servicing it @[AC::Route::GET("/")] - def index : Array(::PlaceOS::Model::Edge) + def index( + @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : Array(::PlaceOS::Model::Edge) # PG full-text search (PPT-2644) - paginate_search(scope_organisations(::PlaceOS::Model::Edge.all), ::PlaceOS::Model::Edge.table_name) + query = narrow_organisation(scope_organisations(::PlaceOS::Model::Edge.all), organisation_id) + paginate_search(query, ::PlaceOS::Model::Edge.table_name) end # return the details of an edge location diff --git a/src/placeos-rest-api/controllers/modules.cr b/src/placeos-rest-api/controllers/modules.cr index ee21c1e8..7c2b58ee 100644 --- a/src/placeos-rest-api/controllers/modules.cr +++ b/src/placeos-rest-api/controllers/modules.cr @@ -182,6 +182,8 @@ module PlaceOS::Api no_logic : Bool = false, @[AC::Param::Info(description: "return only running modules", example: "true")] running : Bool? = nil, + @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, ) : Array(::PlaceOS::Model::Module) # if a system id is present we query the database directly if control_system_id @@ -202,7 +204,7 @@ module PlaceOS::Api end # PG full-text search (PPT-2644) - query = scope_organisations(::PlaceOS::Model::Module.all) + query = narrow_organisation(scope_organisations(::PlaceOS::Model::Module.all), organisation_id) if scope_zones = module_scope_zones # we only want to show modules in use by systems within these zones diff --git a/src/placeos-rest-api/controllers/systems.cr b/src/placeos-rest-api/controllers/systems.cr index 183e97ed..dfbc4216 100644 --- a/src/placeos-rest-api/controllers/systems.cr +++ b/src/placeos-rest-api/controllers/systems.cr @@ -246,9 +246,11 @@ module PlaceOS::Api public : Bool? = nil, @[AC::Param::Info(description: "return systems which are signage", example: "true")] signage : Bool? = nil, + @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, ) : Array(::PlaceOS::Model::ControlSystem) # PG full-text search (PPT-2644) - query = scope_organisations(::PlaceOS::Model::ControlSystem.all) + query = narrow_organisation(scope_organisations(::PlaceOS::Model::ControlSystem.all), organisation_id) # `zone_id` keeps its original AND semantics — a system must # contain *every* listed zone. The intended use is intersection diff --git a/src/placeos-rest-api/controllers/triggers.cr b/src/placeos-rest-api/controllers/triggers.cr index 32e42859..47d0190c 100644 --- a/src/placeos-rest-api/controllers/triggers.cr +++ b/src/placeos-rest-api/controllers/triggers.cr @@ -41,9 +41,16 @@ module PlaceOS::Api # returns the list of available triggers @[AC::Route::GET("/")] - def index : Array(::PlaceOS::Model::Trigger) + def index( + @[AC::Param::Info(description: "only triggers bound to systems owned by this organisation; templates are always included", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + ) : Array(::PlaceOS::Model::Trigger) # PG full-text search (PPT-2644) query = ::PlaceOS::Model::Trigger.all + if organisation_id + ensure_reach!(organisation_id, "organisation") + query = query.where("(control_system_id IS NULL OR organisation_id = ?::uuid)", organisation_id.to_s) + end if ids = tenancy.organisation_ids list = ids.to_a.map(&.to_s) query = if list.empty? diff --git a/src/placeos-rest-api/controllers/users.cr b/src/placeos-rest-api/controllers/users.cr index b66b46ef..a41c1469 100644 --- a/src/placeos-rest-api/controllers/users.cr +++ b/src/placeos-rest-api/controllers/users.cr @@ -150,6 +150,8 @@ module PlaceOS::Api include_metadata : Bool = false, @[AC::Param::Info(description: "admin users can view other domains, ignored for other users", example: "auth-12345")] authority_id : String? = nil, + @[AC::Param::Info(description: "admin users can list the users of every domain owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, ) : Array(UserDetails) # PG full-text search (PPT-2644) # NOTE: email-shaped queries used to be quote-wrapped for an @@ -167,8 +169,8 @@ module PlaceOS::Api ensure_authority_reach!(authority, "domain") query = query.where(authority_id: authority) else - # admins see every domain within reach - query = scope_authorities(query) + # admins see every domain within reach, narrowed to one organisation on request + query = narrow_authorities(scope_authorities(query), organisation_id) end results = paginate_search(query, ::PlaceOS::Model::User.table_name) diff --git a/src/placeos-rest-api/controllers/zones.cr b/src/placeos-rest-api/controllers/zones.cr index ba6fd411..a5f8d1b0 100644 --- a/src/placeos-rest-api/controllers/zones.cr +++ b/src/placeos-rest-api/controllers/zones.cr @@ -156,6 +156,8 @@ module PlaceOS::Api include_children_count : Bool = false, @[AC::Param::Info(description: "with group_id, include anchor zones and their descendants, excluding denied subtrees", example: "true")] descendants : Bool = false, + @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, ) : Array(::PlaceOS::Model::Zone) group_zone_ids = nil if group_id @@ -181,7 +183,7 @@ module PlaceOS::Api # the same for `?parent_id=` as for no param at all parent_id = nil if parent_id.try(&.empty?) - query = scope_organisations(::PlaceOS::Model::Zone.all) + query = narrow_organisation(scope_organisations(::PlaceOS::Model::Zone.all), organisation_id) if group_id && descendants query = query.where("id IN (#{group_descendants_sql})", group_id.to_s) diff --git a/src/placeos-rest-api/utilities/tenancy.cr b/src/placeos-rest-api/utilities/tenancy.cr index 3ca6e146..70d76511 100644 --- a/src/placeos-rest-api/utilities/tenancy.cr +++ b/src/placeos-rest-api/utilities/tenancy.cr @@ -181,6 +181,20 @@ module PlaceOS::Api end end + # Narrows a reach-scoped relation to one organisation the caller asked for. + def narrow_organisation(query, organisation_id : UUID?, column : String = "organisation_id") + return query if organisation_id.nil? + ensure_reach!(organisation_id, "organisation") + query.where("#{column} = ?::uuid", organisation_id.to_s) + end + + # As above for a domain-owned table. + def narrow_authorities(query, organisation_id : UUID?, column : String = "authority_id") + return query if organisation_id.nil? + ensure_reach!(organisation_id, "organisation") + query.where("#{column} IN (SELECT id FROM authority WHERE organisation_id = ?::uuid)", organisation_id.to_s) + end + # As above for tables owned through their domain (`authority_id`). def scope_authorities(query, column : String = "authority_id") ids = tenancy.organisation_ids From 4ddc1fac04477306a9a00a07ba38df22da6c86ad Mon Sep 17 00:00:00 2001 From: Cameron Reeves Date: Wed, 7 Oct 2026 15:37:10 +1100 Subject: [PATCH 04/50] test: PPT-2701 page size on tenancy list assertions Rows left behind by other spec files can push the fixture's rows past the default page, which is what failed in CI. --- spec/controllers/tenancy_spec.cr | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index 0f9377ec..539ed627 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -40,24 +40,24 @@ module PlaceOS::Api it "scopes zones, systems and modules to the caller's organisations" do f = Spec::Tenancy.build - zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.acadian.admin).body) + zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.acadian.admin).body) zones.should contain(f.acadian.org_zone.id) zones.should_not contain(f.ucla.org_zone.id) zones.should_not contain(f.unowned_zone.id) - partner_zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.ntt_staff.support).body) + partner_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.ntt_staff.support).body) partner_zones.should contain(f.acadian.org_zone.id) partner_zones.should contain(f.ntt_staff.org_zone.id) partner_zones.should_not contain(f.ucla.org_zone.id) - cluster_zones = Spec::Tenancy.ids(tenancy_get(Zones.base_route, f.placeos.admin).body) + cluster_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.placeos.admin).body) cluster_zones.should contain(f.ucla.org_zone.id) cluster_zones.should contain(f.unowned_zone.id) - systems = Spec::Tenancy.ids(tenancy_get(Systems.base_route, f.ucla.admin).body) + systems = Spec::Tenancy.ids(tenancy_get("#{Systems.base_route}?limit=500", f.ucla.admin).body) systems.should eq [f.ucla.system.id] - modules = Spec::Tenancy.ids(tenancy_get(Modules.base_route, f.ucla.admin).body) + modules = Spec::Tenancy.ids(tenancy_get("#{Modules.base_route}?limit=500", f.ucla.admin).body) modules.should eq [f.ucla.mod.id] tenancy_get("#{Zones.base_route}tags", f.acadian.admin).status_code.should eq 200 @@ -84,7 +84,7 @@ module PlaceOS::Api it "narrows a list to one organisation on request" do f = Spec::Tenancy.build - narrowed = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", f.placeos.admin).body) + narrowed = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}&limit=500", f.placeos.admin).body) narrowed.should contain(f.ucla.org_zone.id) narrowed.should_not contain(f.acadian.org_zone.id) narrowed.should_not contain(f.unowned_zone.id) @@ -156,7 +156,7 @@ module PlaceOS::Api it "lists and creates domains within reach" do f = Spec::Tenancy.build - domains = Spec::Tenancy.ids(tenancy_get(Domains.base_route, f.acadian.admin).body) + domains = Spec::Tenancy.ids(tenancy_get("#{Domains.base_route}?limit=500", f.acadian.admin).body) domains.should eq [f.acadian.authority.id] tenancy_get("#{Domains.base_route}#{f.ucla.authority.id}", f.acadian.admin).status_code.should eq 404 @@ -175,14 +175,14 @@ module PlaceOS::Api it "lists users within reach only" do f = Spec::Tenancy.build - users = Spec::Tenancy.ids(tenancy_get(Users.base_route, f.acadian.admin).body) + users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?limit=500", f.acadian.admin).body) users.should contain(f.acadian.user.id) users.should_not contain(f.ucla.user.id) tenancy_get("#{Users.base_route}?authority_id=#{f.ucla.authority.id}", f.acadian.admin).status_code.should eq 404 tenancy_get("#{Users.base_route}#{f.ucla.user.id}", f.acadian.admin).status_code.should eq 404 - partner_users = Spec::Tenancy.ids(tenancy_get(Users.base_route, f.ntt_staff.admin).body) + partner_users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?limit=500", f.ntt_staff.admin).body) partner_users.should contain(f.acadian.user.id) partner_users.should_not contain(f.ucla.user.id) end @@ -201,13 +201,13 @@ module PlaceOS::Api template.status_code.should eq 201 # templates are readable by every organisation - templates = Spec::Tenancy.ids(tenancy_get(Triggers.base_route, f.acadian.admin).body) + templates = Spec::Tenancy.ids(tenancy_get("#{Triggers.base_route}?limit=500", f.acadian.admin).body) templates.should contain(JSON.parse(template.body)["id"].to_s) bound = tenancy_post(Triggers.base_route, f.acadian.admin, {name: "Bound #{random_name}", control_system_id: f.acadian.system.id}) bound.status_code.should eq 201 JSON.parse(bound.body)["organisation_id"].to_s.should eq f.acadian.organisation.id.to_s - Spec::Tenancy.ids(tenancy_get(Triggers.base_route, f.ucla.admin).body).should_not contain(JSON.parse(bound.body)["id"].to_s) + Spec::Tenancy.ids(tenancy_get("#{Triggers.base_route}?limit=500", f.ucla.admin).body).should_not contain(JSON.parse(bound.body)["id"].to_s) end end @@ -225,8 +225,8 @@ module PlaceOS::Api tenancy_post(Partners.base_route, f.acadian.admin, {name: "Nope #{random_name}"}).status_code.should eq 403 - Spec::Tenancy.ids(tenancy_get(Organisations.base_route, f.acadian.admin).body).should eq [f.acadian.organisation.id.to_s] - Spec::Tenancy.ids(tenancy_get(Partners.base_route, f.acadian.admin).body).should eq [f.ntt.id.to_s] + Spec::Tenancy.ids(tenancy_get("#{Organisations.base_route}?limit=500", f.acadian.admin).body).should eq [f.acadian.organisation.id.to_s] + Spec::Tenancy.ids(tenancy_get("#{Partners.base_route}?limit=500", f.acadian.admin).body).should eq [f.ntt.id.to_s] tenancy_get("#{Partners.base_route}#{f.management.id}", f.acadian.admin).status_code.should eq 404 client.patch("#{Organisations.base_route}#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "renamed"}.to_json).status_code.should eq 403 From 987ea453e640a5cfe9c0b75124b868d30c37e870 Mon Sep 17 00:00:00 2001 From: Cameron Reeves Date: Wed, 7 Oct 2026 15:50:46 +1100 Subject: [PATCH 05/50] fix: PPT-2701 organisation last-admin rule in the API and a self-cleaning tenancy fixture An organisation admin cannot remove their organisation's last admin; cluster staff can, which is how a domain is torn down. The tenancy spec fixture now tears itself down after each example: the harness clears tables only once per suite, and leaked rows pushed later unfiltered list assertions past the first page. Tracks models at e21d790. --- spec/controllers/tenancy_spec.cr | 52 ++++++++++++++++------- spec/spec_helpers/tenancy.cr | 27 ++++++++++++ src/placeos-rest-api/controllers/users.cr | 15 +++++++ 3 files changed, 79 insertions(+), 15 deletions(-) diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index 539ed627..35fc9aad 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -11,12 +11,21 @@ end module PlaceOS::Api # PPT-526: who can see and touch what across organisations on a shared cluster describe "tenancy" do + fixture = nil.as(Spec::Tenancy::Fixture?) + build = -> { fixture = Spec::Tenancy.build } + before_each { Utils::Tenancy.enforce = true } - after_each { Utils::Tenancy.enforce = false } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end describe "reach" do it "resolves cluster, partner and organisation reach" do - f = Spec::Tenancy.build + f = build.call.not_nil! cluster = JSON.parse(tenancy_get("#{Organisations.base_route}current", f.placeos.admin).body) cluster["reach"].should eq "cluster" @@ -38,7 +47,7 @@ module PlaceOS::Api describe "estate lists" do it "scopes zones, systems and modules to the caller's organisations" do - f = Spec::Tenancy.build + f = build.call.not_nil! zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.acadian.admin).body) zones.should contain(f.acadian.org_zone.id) @@ -64,7 +73,7 @@ module PlaceOS::Api end it "answers 404 for another organisation's rows and 200 for its own" do - f = Spec::Tenancy.build + f = build.call.not_nil! tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.acadian.admin).status_code.should eq 404 tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.acadian.admin).status_code.should eq 200 @@ -82,7 +91,7 @@ module PlaceOS::Api end it "narrows a list to one organisation on request" do - f = Spec::Tenancy.build + f = build.call.not_nil! narrowed = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}&limit=500", f.placeos.admin).body) narrowed.should contain(f.ucla.org_zone.id) @@ -100,7 +109,7 @@ module PlaceOS::Api end it "only logs when enforcement is off" do - f = Spec::Tenancy.build + f = build.call.not_nil! Utils::Tenancy.enforce = false tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.acadian.admin).status_code.should eq 200 end @@ -108,7 +117,7 @@ module PlaceOS::Api describe "estate writes" do it "owns new zones through the caller or the parent" do - f = Spec::Tenancy.build + f = build.call.not_nil! root = tenancy_post(Zones.base_route, f.acadian.admin, {name: "Acadian root #{random_name}", tags: ["building"]}) root.status_code.should eq 201 @@ -129,7 +138,7 @@ module PlaceOS::Api end it "owns new systems through their zones and refuses mixed zones" do - f = Spec::Tenancy.build + f = build.call.not_nil! own = tenancy_post(Systems.base_route, f.acadian.admin, {name: "Room #{random_name}", zones: [f.acadian.building.id]}) own.status_code.should eq 201 @@ -142,7 +151,7 @@ module PlaceOS::Api end it "keeps modules inside the system's organisation" do - f = Spec::Tenancy.build + f = build.call.not_nil! attach = client.put("#{Systems.base_route}#{f.acadian.system.id}/module/#{f.ucla.mod.id}", headers: Spec::Tenancy.headers(f.acadian.admin)) attach.status_code.should eq 404 @@ -154,7 +163,7 @@ module PlaceOS::Api describe "domains and users" do it "lists and creates domains within reach" do - f = Spec::Tenancy.build + f = build.call.not_nil! domains = Spec::Tenancy.ids(tenancy_get("#{Domains.base_route}?limit=500", f.acadian.admin).body) domains.should eq [f.acadian.authority.id] @@ -173,7 +182,7 @@ module PlaceOS::Api end it "lists users within reach only" do - f = Spec::Tenancy.build + f = build.call.not_nil! users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?limit=500", f.acadian.admin).body) users.should contain(f.acadian.user.id) @@ -188,9 +197,22 @@ module PlaceOS::Api end end + describe "last organisation admin" do + it "refuses an organisation admin removing their last admin, allows cluster staff" do + f = build.call.not_nil! + + client.delete("#{Users.base_route}#{f.acadian.admin.id}", headers: Spec::Tenancy.headers(f.acadian.admin)).status_code.should eq 403 + + second = Model::Generator.user(f.acadian.authority, admin: true).save! + client.delete("#{Users.base_route}#{second.id}", headers: Spec::Tenancy.headers(f.acadian.admin)).status_code.should eq 202 + + client.delete("#{Users.base_route}#{f.acadian.admin.id}", headers: Spec::Tenancy.headers(f.placeos.admin)).status_code.should eq 202 + end + end + describe "cluster-only resources" do it "hides brokers and trigger templates' writes from organisation admins" do - f = Spec::Tenancy.build + f = build.call.not_nil! tenancy_get(Brokers.base_route, f.acadian.admin).status_code.should eq 403 tenancy_get(Brokers.base_route, f.placeos.admin).status_code.should eq 200 @@ -213,7 +235,7 @@ module PlaceOS::Api describe "organisations, partners and grants" do it "lets cluster admins manage the hierarchy and others read their own" do - f = Spec::Tenancy.build + f = build.call.not_nil! partner = tenancy_post(Partners.base_route, f.placeos.admin, {name: "Integrator #{random_name}"}) partner.status_code.should eq 201 @@ -233,7 +255,7 @@ module PlaceOS::Api end it "widens reach through live grants" do - f = Spec::Tenancy.build + f = build.call.not_nil! tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 @@ -254,7 +276,7 @@ module PlaceOS::Api end it "claims an unowned zone tree for an organisation" do - f = Spec::Tenancy.build + f = build.call.not_nil! claimed = tenancy_post("#{Organisations.base_route}#{f.ucla.organisation.id}/claim", f.placeos.admin, {zone_ids: [f.unowned_zone.id]}) claimed.status_code.should eq 200 diff --git a/spec/spec_helpers/tenancy.cr b/spec/spec_helpers/tenancy.cr index c289e983..15e5922c 100644 --- a/spec/spec_helpers/tenancy.cr +++ b/spec/spec_helpers/tenancy.cr @@ -89,6 +89,33 @@ module PlaceOS::Api::Spec::Tenancy ) end + # Removes everything a fixture and its example created. The suite only + # clears tables once, so each example must leave the database as it found + # it: other specs list zones and users without a page size. + def self.teardown(f : Fixture) + none = [] of ::PgORM::Value + Model::Module.where("organisation_id IS NOT NULL", none).to_a.each { |row| row.destroy rescue nil } + Model::ControlSystem.where("organisation_id IS NOT NULL", none).to_a.each { |row| row.destroy rescue nil } + Model::Trigger.where("organisation_id IS NOT NULL OR name LIKE 'Template %'", none).to_a.each { |row| row.destroy rescue nil } + Model::Edge.where("organisation_id IS NOT NULL", none).to_a.each { |row| row.destroy rescue nil } + Model::Zone.where("organisation_id IS NOT NULL", none).to_a + .sort_by { |zone| zone.parent_id.presence ? 0 : 1 } + .each { |row| row.destroy rescue nil } + [f.unowned_system, f.unowned_zone].each { |row| row.destroy rescue nil } + + Model::Grant.clear + # fixture domains and anything an example created under them; localhost stays + Model::Authority.where("domain LIKE '%.test'", none).to_a.each { |row| row.destroy rescue nil } + [f.placeos.user, f.placeos.support, f.placeos.admin].each { |row| row.destroy rescue nil } + localhost = Model::Authority.find?(f.placeos.authority.id.as(String)) + if localhost + localhost.organisation_id = nil + localhost.save! + end + Model::Organisation.clear + Model::Partner.clear + end + # Bearer + Host headers for a user on their own domain def self.headers(user : Model::User) : HTTP::Headers authority = user.authority.as(Model::Authority) diff --git a/src/placeos-rest-api/controllers/users.cr b/src/placeos-rest-api/controllers/users.cr index a41c1469..43e2c9f8 100644 --- a/src/placeos-rest-api/controllers/users.cr +++ b/src/placeos-rest-api/controllers/users.cr @@ -256,12 +256,27 @@ module PlaceOS::Api user.deleted = true raise Error::ModelValidation.new(user.errors) unless user.save else + ensure_organisation_admin_remains!(user) user_id = user.id user.destroy spawn { Api::Metadata.signal_metadata(current_authority.not_nil!.id.to_s, :destroy_all, {parent_id: user_id}) } end end + # An organisation admin cannot remove their organisation's last admin. + # Cluster admins may, which is how a whole domain gets torn down. + protected def ensure_organisation_admin_remains!(target : ::PlaceOS::Model::User) : Nil + return unless target.sys_admin + return if tenancy.cluster? + organisation_id = ::PlaceOS::Model::Authority.find?(target.authority_id.as(String)).try(&.organisation_id) + return unless organisation_id + remaining = ::PlaceOS::Model::User + .where(sys_admin: true, deleted: false) + .where("authority_id IN (SELECT id FROM authority WHERE organisation_id = ?::uuid)", organisation_id.to_s) + .count + raise Error::Forbidden.new("at least one organisation admin must remain") if remaining <= 1 + end + # undelete a user @[AC::Route::POST("/:id/revive")] def revive From 219c592296fa11b681b61dd35589daf21025bffd Mon Sep 17 00:00:00 2001 From: Stephen von Takach Date: Fri, 6 Nov 2026 16:33:41 +1100 Subject: [PATCH 06/50] fix: PPT-2701 reach on the routes added to master since enforcement - History: change history spans every organisation's records and undelete restores any of them, so it's cluster admins only. - Source resync: proxies a cluster-wide MQTT resync, cluster admins only. - Map AI edits: support users skipped the zone visibility check for every zone on the cluster; the zone must now be within reach. Module creation with `system_id` (also new on master) takes the system's organisation and requires reach over it, resolved in the rebase. Co-Authored-By: Claude Opus 5.5 --- spec/controllers/tenancy_spec.cr | 20 ++++++++++++++++++++ src/placeos-rest-api/controllers/history.cr | 2 ++ src/placeos-rest-api/controllers/map_ai.cr | 4 +++- src/placeos-rest-api/controllers/root.cr | 3 +++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index 35fc9aad..b437307f 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -233,6 +233,26 @@ module PlaceOS::Api end end + describe "routes added since the reach enforcement" do + it "keeps change history and the source resync to cluster admins" do + f = build.call.not_nil! + + tenancy_get(History.base_route, f.acadian.admin).status_code.should eq 403 + tenancy_get(History.base_route, f.placeos.admin).status_code.should eq 200 + tenancy_post(File.join(History.base_route, "undelete?resource_type=zone&resource_id=#{f.ucla.org_zone.id}"), f.acadian.admin, nil).status_code.should eq 403 + + tenancy_post("/api/engine/v2/source/resync", f.acadian.admin, nil).status_code.should eq 403 + tenancy_get("/api/engine/v2/source/resync", f.acadian.admin).status_code.should eq 403 + end + + it "hides another organisation's zones from map edits, support users included" do + f = build.call.not_nil! + + result = tenancy_post(File.join(MapAI.base_route, "edit"), f.acadian.support, {zone_id: f.ucla.org_zone.id, instruction: "x", context: JSON.parse(File.read(File.join(__DIR__, "../fixtures/map_ai/context.json")))}) + result.status_code.should eq 404 + end + end + describe "organisations, partners and grants" do it "lets cluster admins manage the hierarchy and others read their own" do f = build.call.not_nil! diff --git a/src/placeos-rest-api/controllers/history.cr b/src/placeos-rest-api/controllers/history.cr index ed1609ef..94771a62 100644 --- a/src/placeos-rest-api/controllers/history.cr +++ b/src/placeos-rest-api/controllers/history.cr @@ -14,6 +14,8 @@ module PlaceOS::Api before_action :can_write, only: [:undelete] before_action :check_admin + # history spans every organisation's records + before_action :check_cluster_admin ############################################################################################### diff --git a/src/placeos-rest-api/controllers/map_ai.cr b/src/placeos-rest-api/controllers/map_ai.cr index a19c1e72..c7608775 100644 --- a/src/placeos-rest-api/controllers/map_ai.cr +++ b/src/placeos-rest-api/controllers/map_ai.cr @@ -197,7 +197,9 @@ module PlaceOS::Api raise Error::ModelValidation.new([Error::Field.new(:zone_id, "is required")]) if params.zone_id.blank? zone = ::PlaceOS::Model::Zone.find?(params.zone_id) - raise Error::NotFound.new("no such zone") if zone.nil? || !zone_visible?(zone) + raise Error::NotFound.new("no such zone") if zone.nil? + ensure_reach!(zone) + raise Error::NotFound.new("no such zone") unless zone_visible?(zone) raise Error::Forbidden.new("you cannot change this zone's map") unless zone_updatable?(zone) context = params.context diff --git a/src/placeos-rest-api/controllers/root.cr b/src/placeos-rest-api/controllers/root.cr index 6359466f..d4216c64 100644 --- a/src/placeos-rest-api/controllers/root.cr +++ b/src/placeos-rest-api/controllers/root.cr @@ -23,6 +23,9 @@ module PlaceOS::Api before_action :can_write_guest, only: [:signal] + # resyncing source's MQTT state is cluster infrastructure + before_action :check_cluster_admin, only: [:source_resync, :source_resync_status] + # Healthcheck ############################################################################################### From 7f34b913a106ffba97b46df0a83324255867e14f Mon Sep 17 00:00:00 2001 From: Stephen von Takach Date: Fri, 6 Nov 2026 16:33:41 +1100 Subject: [PATCH 07/50] chore: PPT-2701 track the rebased models tenancy branch and regenerate the OpenAPI document models at b502009 (pg-orm 2.5.3). Co-Authored-By: Claude Opus 5.5 --- OPENAPI_DOC.yml | 4089 +++++++++++++++++++++++++++++++++++++---------- shard.lock | 6 +- 2 files changed, 3221 insertions(+), 874 deletions(-) diff --git a/OPENAPI_DOC.yml b/OPENAPI_DOC.yml index 119215ed..c6cb61c3 100644 --- a/OPENAPI_DOC.yml +++ b/OPENAPI_DOC.yml @@ -9044,6 +9044,15 @@ paths: - Domains operationId: PlaceOS::Api::Domains_index parameters: + - name: organisation_id + in: query + description: only rows owned by this organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -9169,7 +9178,11 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' post: - summary: add a new domain + summary: add a new domain. Organisation admins create domains in their own + description: 'add a new domain. Organisation admins create domains in their + own + + organisation; cluster admins name the organisation.' tags: - Domains operationId: PlaceOS::Api::Domains_create @@ -9179,7 +9192,16 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Model.Authority' required: true - parameters: [] + parameters: + - name: organisation_id + in: query + description: the organisation that owns the new domain + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" responses: "201": description: Created @@ -9482,6 +9504,15 @@ paths: required: true schema: type: string + - name: organisation_id + in: query + description: move the domain to this organisation (cluster admins only) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" responses: "200": description: OK @@ -9676,6 +9707,15 @@ paths: required: true schema: type: string + - name: organisation_id + in: query + description: move the domain to this organisation (cluster admins only) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" responses: "200": description: OK @@ -11598,6 +11638,15 @@ paths: anyOf: - type: boolean - type: "null" + - name: organisation_id + in: query + description: only rows owned by this organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -11742,6 +11791,16 @@ paths: anyOf: - type: "null" - type: string + - name: organisation_id + in: query + description: the organisation that owns a module not bound to a system (cluster + admins only) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" responses: "201": description: Created @@ -13477,6 +13536,15 @@ paths: anyOf: - type: boolean - type: "null" + - name: organisation_id + in: query + description: only rows owned by this organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -13602,7 +13670,11 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' post: - summary: adds a new system + summary: adds a new system. The system belongs to its zones' organisation, or + description: 'adds a new system. The system belongs to its zones'' organisation, + or + + the caller''s when the zones are unowned.' tags: - Systems operationId: PlaceOS::Api::Systems_create @@ -15790,6 +15862,15 @@ paths: - Edges operationId: PlaceOS::Api::Edges_index parameters: + - name: organisation_id + in: query + description: only rows owned by this organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -17864,54 +17945,63 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/groups: - summary: Groups of users, used to grant permissions to zones and features - get: - summary: List groups. sys_admin sees all within the current authority; other - description: 'List groups. sys_admin sees all within the current authority; - other - - users see only groups they''re a member of (direct or transitive). + /api/engine/v2/grants: + summary: 'Grants: explicit, revocable, optionally time-boxed reach for a user + into a' + description: 'Grants: explicit, revocable, optionally time-boxed reach for a user + into a - Optionally filter by `parent_id` for tree queries (pass the - - literal string `root` for root-level groups). Pass `q` for a - - case-insensitive substring search on `name`.' + partner, organisation or domain they do not belong to (PPT-526)' + get: + summary: grants on a scope, or held by a user tags: - - Groups - operationId: PlaceOS::Api::Groups_index + - Grants + operationId: PlaceOS::Api::Grants_index parameters: - - name: parent_id + - name: scope_type in: query - description: filter by parent group id; pass 'root' for root-level groups + description: partner, organisation or authority + example: organisation schema: anyOf: - type: "null" - type: string - - name: q + - name: scope_id in: query - description: case-insensitive substring search on name (SQL ILIKE) + description: the id of the partner, organisation or domain + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f schema: anyOf: - type: "null" - type: string - - name: include_children_count + - name: user_id in: query - description: include children_count for each group (useful for tree views) - example: true + description: grants held by this user + example: user-1234 schema: - type: boolean + anyOf: + - type: "null" + - type: string + - name: q + in: query + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' + schema: + type: string - name: limit in: query + description: the maximum number of results to return + example: 10000 schema: type: integer - format: Int32 + format: UInt32 - name: offset in: query + description: the starting offset of the result set, used to implement pagination schema: type: integer - format: Int32 + format: UInt32 - name: ref in: query description: deprecated, ignored — pagination follows the `Link` header's @@ -17937,7 +18027,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Model.Group' + $ref: '#/components/schemas/PlaceOS.Model.Grant' "409": description: Conflict content: @@ -18017,18 +18107,14 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' post: - summary: Create a new group. A root group (parent_id nil) requires - description: 'Create a new group. A root group (parent_id nil) requires - - sys_admin; a child group requires Manage on the parent.' tags: - - Groups - operationId: PlaceOS::Api::Groups_create + - Grants + operationId: PlaceOS::Api::Grants_create requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Group' + $ref: '#/components/schemas/PlaceOS.Api.Grants.GrantBody' required: true parameters: [] responses: @@ -18037,7 +18123,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Group' + $ref: '#/components/schemas/PlaceOS.Model.Grant' "409": description: Conflict content: @@ -18116,13 +18202,17 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/groups/{id}: - summary: Groups of users, used to grant permissions to zones and features + /api/engine/v2/grants/{id}: + summary: 'Grants: explicit, revocable, optionally time-boxed reach for a user + into a' + description: 'Grants: explicit, revocable, optionally time-boxed reach for a user + into a + + partner, organisation or domain they do not belong to (PPT-526)' get: - summary: Show group details. Visible if sys_admin or a member. tags: - - Groups - operationId: PlaceOS::Api::Groups_show + - Grants + operationId: PlaceOS::Api::Grants_show parameters: - name: id in: path @@ -18136,7 +18226,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Group' + $ref: '#/components/schemas/PlaceOS.Model.Grant' "409": description: Conflict content: @@ -18215,20 +18305,10 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - put: - summary: Update the group (name / description / parent / features). - description: 'Update the group (name / description / parent / features). - - Changing `features` requires Manage on the parent group.' + delete: tags: - - Groups - operationId: PlaceOS::Api::Groups_update - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Model.Group' - required: true + - Grants + operationId: PlaceOS::Api::Grants_destroy parameters: - name: id in: path @@ -18236,13 +18316,161 @@ paths: schema: type: string format: uuid + responses: + "202": + description: Accepted + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/groups: + summary: Groups of users, used to grant permissions to zones and features + get: + summary: List groups. sys_admin sees all within the current authority; other + description: 'List groups. sys_admin sees all within the current authority; + other + + users see only groups they''re a member of (direct or transitive). + + Optionally filter by `parent_id` for tree queries (pass the + + literal string `root` for root-level groups). Pass `q` for a + + case-insensitive substring search on `name`.' + tags: + - Groups + operationId: PlaceOS::Api::Groups_index + parameters: + - name: parent_id + in: query + description: filter by parent group id; pass 'root' for root-level groups + schema: + anyOf: + - type: "null" + - type: string + - name: q + in: query + description: case-insensitive substring search on name (SQL ILIKE) + schema: + anyOf: + - type: "null" + - type: string + - name: include_children_count + in: query + description: include children_count for each group (useful for tree views) + example: true + schema: + type: boolean + - name: limit + in: query + schema: + type: integer + format: Int32 + - name: offset + in: query + schema: + type: integer + format: Int32 + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset + schema: + anyOf: + - type: "null" + - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Group' + type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.Group' "409": description: Conflict content: @@ -18321,11 +18549,113 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - delete: - summary: Destroy a group (cascades children and junctions via FK). + post: + summary: Create a new group. A root group (parent_id nil) requires + description: 'Create a new group. A root group (parent_id nil) requires + + sys_admin; a child group requires Manage on the parent.' tags: - Groups - operationId: PlaceOS::Api::Groups_destroy + operationId: PlaceOS::Api::Groups_create + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Group' + required: true + parameters: [] + responses: + "201": + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Group' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/groups/{id}: + summary: Groups of users, used to grant permissions to zones and features + get: + summary: Show group details. Visible if sys_admin or a member. + tags: + - Groups + operationId: PlaceOS::Api::Groups_show parameters: - name: id in: path @@ -18334,8 +18664,12 @@ paths: type: string format: uuid responses: - "202": - description: Accepted + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Group' "409": description: Conflict content: @@ -18414,14 +18748,14 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - patch: + put: summary: Update the group (name / description / parent / features). description: 'Update the group (name / description / parent / features). Changing `features` requires Manage on the parent group.' tags: - Groups - operationId: PlaceOS::Api::Groups_update_2 + operationId: PlaceOS::Api::Groups_update requestBody: content: application/json: @@ -18520,18 +18854,11 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/groups/{id}/features: - summary: Groups of users, used to grant permissions to zones and features - get: - summary: Effective feature flags for this group. - description: 'Effective feature flags for this group. - - The group''s own `features` merged over every ancestor''s, per subsystem, - - with the deepest group winning each key. Shape: `{subsystem => {key => value}}`.' + delete: + summary: Destroy a group (cascades children and junctions via FK). tags: - Groups - operationId: PlaceOS::Api::Groups_features + operationId: PlaceOS::Api::Groups_destroy parameters: - name: id in: path @@ -18539,21 +18866,9 @@ paths: schema: type: string format: uuid - - name: subsystem - in: query - description: only return this subsystem's features - example: signage - schema: - anyOf: - - type: "null" - - type: string responses: - "200": - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/Hash-oString-nHash-oString-nJSON.Any-c-c' + "202": + description: Accepted "409": description: Conflict content: @@ -18632,38 +18947,34 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/groups/ad_groups/sync: - summary: Groups of users, used to grant permissions to zones and features - post: - summary: Sync a user's group memberships with their AD groups. - description: 'Sync a user''s group memberships with their AD groups. - - Uses each group''s `ad_group_mappings` to add the user to mapped groups - - and remove memberships that were auto-assigned from AD groups the user - - has left; manually added memberships are untouched. Returns the user''s + patch: + summary: Update the group (name / description / parent / features). + description: 'Update the group (name / description / parent / features). - group memberships in the current authority. Requires support or sys_admin.' + Changing `features` requires Manage on the parent group.' tags: - Groups - operationId: PlaceOS::Api::Groups_sync_ad_groups + operationId: PlaceOS::Api::Groups_update_2 requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.Groups.AdGroupSync' + $ref: '#/components/schemas/PlaceOS.Model.Group' required: true - parameters: [] + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid responses: "200": description: OK content: application/json: schema: - type: array - items: - $ref: '#/components/schemas/PlaceOS.Model.GroupUser' + $ref: '#/components/schemas/PlaceOS.Model.Group' "409": description: Conflict content: @@ -18742,16 +19053,28 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/groups/current: + /api/engine/v2/groups/{id}/features: summary: Groups of users, used to grant permissions to zones and features get: + summary: Effective feature flags for this group. + description: 'Effective feature flags for this group. + + The group''s own `features` merged over every ancestor''s, per subsystem, + + with the deepest group winning each key. Shape: `{subsystem => {key => value}}`.' tags: - Groups - operationId: PlaceOS::Api::Groups_current + operationId: PlaceOS::Api::Groups_features parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid - name: subsystem in: query - description: filter to groups participating in this subsystem (e.g. 'signage') + description: only return this subsystem's features example: signage schema: anyOf: @@ -18763,9 +19086,7 @@ paths: content: application/json: schema: - type: array - items: - $ref: '#/components/schemas/PlaceOS.Api.Groups.CurrentGroup' + $ref: '#/components/schemas/Hash-oString-nHash-oString-nJSON.Any-c-c' "409": description: Conflict content: @@ -18844,63 +19165,29 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_history: - summary: Audit history of changes to groups and their memberships - get: - summary: List audit entries, newest first. sys_admin sees everything; other - description: 'List audit entries, newest first. sys_admin sees everything; other + /api/engine/v2/groups/ad_groups/sync: + summary: Groups of users, used to grant permissions to zones and features + post: + summary: Sync a user's group memberships with their AD groups. + description: 'Sync a user''s group memberships with their AD groups. - callers must pass `group_id=` and have Manage on it.' + Uses each group''s `ad_group_mappings` to add the user to mapped groups + + and remove memberships that were auto-assigned from AD groups the user + + has left; manually added memberships are untouched. Returns the user''s + + group memberships in the current authority. Requires support or sys_admin.' tags: - - History - operationId: PlaceOS::Api::Groups::History_index - parameters: - - name: group_id - in: query - description: only return changes to this group and its memberships - example: 0192d1c8-2f0e-7cc1-9d2a-6f1c7e1b3a51 - schema: - anyOf: - - type: string - format: uuid - - type: "null" - - name: limit - in: query - description: the maximum number of results to return - example: 100 - schema: - type: integer - format: Int32 - - name: offset - in: query - description: the starting offset of the result set, used to implement pagination - schema: - type: integer - format: Int32 - - name: q - in: query - description: 'filters results by the given text: a record matches when any - word matches its searchable fields as a whole word, and the last word also - matches as a prefix (search as you type)' - schema: - type: string - - name: ref - in: query - description: deprecated, ignored — pagination follows the `Link` header's - offset - schema: - anyOf: - - type: "null" - - type: string - - name: fields - in: query - description: deprecated, ignored — search covers the resource's indexed fields - style: form - explode: false - schema: - type: array - items: - type: string + - Groups + operationId: PlaceOS::Api::Groups_sync_ad_groups + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Groups.AdGroupSync' + required: true + parameters: [] responses: "200": description: OK @@ -18909,7 +19196,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Model.History' + $ref: '#/components/schemas/PlaceOS.Model.GroupUser' "409": description: Conflict content: @@ -18988,26 +19275,30 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_history/{id}: - summary: Audit history of changes to groups and their memberships + /api/engine/v2/groups/current: + summary: Groups of users, used to grant permissions to zones and features get: tags: - - History - operationId: PlaceOS::Api::Groups::History_show + - Groups + operationId: PlaceOS::Api::Groups_current parameters: - - name: id - in: path - required: true + - name: subsystem + in: query + description: filter to groups participating in this subsystem (e.g. 'signage') + example: signage schema: - type: string - format: uuid + anyOf: + - type: "null" + - type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.History' + type: array + items: + $ref: '#/components/schemas/PlaceOS.Api.Groups.CurrentGroup' "409": description: Conflict content: @@ -19086,19 +19377,21 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_invitations: - summary: Invitations for users to join groups + /api/engine/v2/group_history: + summary: Audit history of changes to groups and their memberships get: - summary: List invitations. Optionally filter by `group_id`. Non-admin - description: 'List invitations. Optionally filter by `group_id`. Non-admin + summary: List audit entries, newest first. sys_admin sees everything; other + description: 'List audit entries, newest first. sys_admin sees everything; other - callers must have Manage on the target group.' + callers must pass `group_id=` and have Manage on it.' tags: - - Invitations - operationId: PlaceOS::Api::Groups::Invitations_index + - History + operationId: PlaceOS::Api::Groups::History_index parameters: - name: group_id in: query + description: only return changes to this group and its memberships + example: 0192d1c8-2f0e-7cc1-9d2a-6f1c7e1b3a51 schema: anyOf: - type: string @@ -19106,11 +19399,14 @@ paths: - type: "null" - name: limit in: query + description: the maximum number of results to return + example: 100 schema: type: integer format: Int32 - name: offset in: query + description: the starting offset of the result set, used to implement pagination schema: type: integer format: Int32 @@ -19146,7 +19442,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Model.GroupInvitation' + $ref: '#/components/schemas/PlaceOS.Model.History' "409": description: Conflict content: @@ -19225,30 +19521,26 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - post: - summary: Custom body-driven create so we can return the plaintext secret - description: 'Custom body-driven create so we can return the plaintext secret - - alongside the invitation. Authorisation check is inline here (not - - a before_action) so the body is consumed exactly once.' + /api/engine/v2/group_history/{id}: + summary: Audit history of changes to groups and their memberships + get: tags: - - Invitations - operationId: PlaceOS::Api::Groups::Invitations_create - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Api.Groups.Invitations.InvitationCreatePayload' + - History + operationId: PlaceOS::Api::Groups::History_show + parameters: + - name: id + in: path required: true - parameters: [] + schema: + type: string + format: uuid responses: - "201": - description: Created + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.Groups.Invitations.InvitationCreatedResponse' + $ref: '#/components/schemas/PlaceOS.Model.History' "409": description: Conflict content: @@ -19327,26 +19619,67 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_invitations/{id}: + /api/engine/v2/group_invitations: summary: Invitations for users to join groups get: + summary: List invitations. Optionally filter by `group_id`. Non-admin + description: 'List invitations. Optionally filter by `group_id`. Non-admin + + callers must have Manage on the target group.' tags: - Invitations - operationId: PlaceOS::Api::Groups::Invitations_show + operationId: PlaceOS::Api::Groups::Invitations_index parameters: - - name: id - in: path - required: true + - name: group_id + in: query + schema: + anyOf: + - type: string + format: uuid + - type: "null" + - name: limit + in: query + schema: + type: integer + format: Int32 + - name: offset + in: query + schema: + type: integer + format: Int32 + - name: q + in: query + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' schema: type: string - format: uuid + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset + schema: + anyOf: + - type: "null" + - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupInvitation' + type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.GroupInvitation' "409": description: Conflict content: @@ -19425,20 +19758,30 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - delete: + post: + summary: Custom body-driven create so we can return the plaintext secret + description: 'Custom body-driven create so we can return the plaintext secret + + alongside the invitation. Authorisation check is inline here (not + + a before_action) so the body is consumed exactly once.' tags: - Invitations - operationId: PlaceOS::Api::Groups::Invitations_destroy - parameters: - - name: id - in: path + operationId: PlaceOS::Api::Groups::Invitations_create + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Groups.Invitations.InvitationCreatePayload' required: true - schema: - type: string - format: uuid + parameters: [] responses: - "202": - description: Accepted + "201": + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Groups.Invitations.InvitationCreatedResponse' "409": description: Conflict content: @@ -19517,16 +19860,12 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_invitations/{id}/accept: + /api/engine/v2/group_invitations/{id}: summary: Invitations for users to join groups - post: - summary: Accept the invitation, materialising it into a GroupUser for the - description: 'Accept the invitation, materialising it into a GroupUser for the - - current user. The invitation row is destroyed on success.' + get: tags: - Invitations - operationId: PlaceOS::Api::Groups::Invitations_accept + operationId: PlaceOS::Api::Groups::Invitations_show parameters: - name: id in: path @@ -19540,7 +19879,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupUser' + $ref: '#/components/schemas/PlaceOS.Model.GroupInvitation' "409": description: Conflict content: @@ -19619,75 +19958,20 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_users: - summary: Group memberships, the users in each group and their permissions - get: - summary: GroupUser rows. Optional `group_id` scopes to one group; - description: 'GroupUser rows. Optional `group_id` scopes to one group; - - `user_id=me` returns the current user''s own rows. Non-admin - - callers without Manage on the specified group see only their own.' + delete: tags: - - Users - operationId: PlaceOS::Api::Groups::Users_index + - Invitations + operationId: PlaceOS::Api::Groups::Invitations_destroy parameters: - - name: group_id - in: query - schema: - anyOf: - - type: string - format: uuid - - type: "null" - - name: user_id - in: query - schema: - anyOf: - - type: "null" - - type: string - - name: limit - in: query - schema: - type: integer - format: Int32 - - name: offset - in: query - schema: - type: integer - format: Int32 - - name: q - in: query - description: 'filters results by the given text: a record matches when any - word matches its searchable fields as a whole word, and the last word also - matches as a prefix (search as you type)' + - name: id + in: path + required: true schema: type: string - - name: ref - in: query - description: deprecated, ignored — pagination follows the `Link` header's - offset - schema: - anyOf: - - type: "null" - - type: string - - name: fields - in: query - description: deprecated, ignored — search covers the resource's indexed fields - style: form - explode: false - schema: - type: array - items: - type: string + format: uuid responses: - "200": - description: OK - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/PlaceOS.Model.GroupUser' + "202": + description: Accepted "409": description: Conflict content: @@ -19766,20 +20050,26 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/group_invitations/{id}/accept: + summary: Invitations for users to join groups post: + summary: Accept the invitation, materialising it into a GroupUser for the + description: 'Accept the invitation, materialising it into a GroupUser for the + + current user. The invitation row is destroyed on success.' tags: - - Users - operationId: PlaceOS::Api::Groups::Users_create - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupUser' + - Invitations + operationId: PlaceOS::Api::Groups::Invitations_accept + parameters: + - name: id + in: path required: true - parameters: [] + schema: + type: string + format: uuid responses: - "201": - description: Created + "200": + description: OK content: application/json: schema: @@ -19862,31 +20152,75 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_users/{user_id}/{group_id}: + /api/engine/v2/group_users: summary: Group memberships, the users in each group and their permissions get: + summary: GroupUser rows. Optional `group_id` scopes to one group; + description: 'GroupUser rows. Optional `group_id` scopes to one group; + + `user_id=me` returns the current user''s own rows. Non-admin + + callers without Manage on the specified group see only their own.' tags: - Users - operationId: PlaceOS::Api::Groups::Users_show + operationId: PlaceOS::Api::Groups::Users_index parameters: + - name: group_id + in: query + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: user_id - in: path - required: true + in: query schema: - type: string - - name: group_id - in: path - required: true + anyOf: + - type: "null" + - type: string + - name: limit + in: query + schema: + type: integer + format: Int32 + - name: offset + in: query + schema: + type: integer + format: Int32 + - name: q + in: query + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' schema: type: string - format: uuid + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset + schema: + anyOf: + - type: "null" + - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupUser' + type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.GroupUser' "409": description: Conflict content: @@ -19965,31 +20299,20 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - put: + post: tags: - Users - operationId: PlaceOS::Api::Groups::Users_update + operationId: PlaceOS::Api::Groups::Users_create requestBody: content: application/json: schema: $ref: '#/components/schemas/PlaceOS.Model.GroupUser' required: true - parameters: - - name: user_id - in: path - required: true - schema: - type: string - - name: group_id - in: path - required: true - schema: - type: string - format: uuid + parameters: [] responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -20072,10 +20395,12 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - delete: + /api/engine/v2/group_users/{user_id}/{group_id}: + summary: Group memberships, the users in each group and their permissions + get: tags: - Users - operationId: PlaceOS::Api::Groups::Users_destroy + operationId: PlaceOS::Api::Groups::Users_show parameters: - name: user_id in: path @@ -20089,8 +20414,12 @@ paths: type: string format: uuid responses: - "202": - description: Accepted + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.GroupUser' "409": description: Conflict content: @@ -20169,10 +20498,10 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - patch: + put: tags: - Users - operationId: PlaceOS::Api::Groups::Users_update_2 + operationId: PlaceOS::Api::Groups::Users_update requestBody: content: application/json: @@ -20276,70 +20605,25 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_zones: - summary: The zones a group has access to, and the permissions it has there - get: - summary: List GroupZone rows. Filterable by group_id / zone_id. + delete: tags: - - Zones - operationId: PlaceOS::Api::Groups::Zones_index + - Users + operationId: PlaceOS::Api::Groups::Users_destroy parameters: - - name: group_id - in: query - schema: - anyOf: - - type: string - format: uuid - - type: "null" - - name: zone_id - in: query - schema: - anyOf: - - type: "null" - - type: string - - name: limit - in: query - schema: - type: integer - format: Int32 - - name: offset - in: query - schema: - type: integer - format: Int32 - - name: q - in: query - description: 'filters results by the given text: a record matches when any - word matches its searchable fields as a whole word, and the last word also - matches as a prefix (search as you type)' + - name: user_id + in: path + required: true schema: type: string - - name: ref - in: query - description: deprecated, ignored — pagination follows the `Link` header's - offset - schema: - anyOf: - - type: "null" - - type: string - - name: fields - in: query - description: deprecated, ignored — search covers the resource's indexed fields - style: form - explode: false + - name: group_id + in: path + required: true schema: - type: array - items: - type: string + type: string + format: uuid responses: - "200": - description: OK - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + "202": + description: Accepted "409": description: Conflict content: @@ -20418,24 +20702,35 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - post: + patch: tags: - - Zones - operationId: PlaceOS::Api::Groups::Zones_create + - Users + operationId: PlaceOS::Api::Groups::Users_update_2 requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + $ref: '#/components/schemas/PlaceOS.Model.GroupUser' required: true - parameters: [] + parameters: + - name: user_id + in: path + required: true + schema: + type: string + - name: group_id + in: path + required: true + schema: + type: string + format: uuid responses: - "201": - description: Created + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + $ref: '#/components/schemas/PlaceOS.Model.GroupUser' "409": description: Conflict content: @@ -20514,31 +20809,269 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/group_zones/{group_id}/{zone_id}: + /api/engine/v2/group_zones: summary: The zones a group has access to, and the permissions it has there get: + summary: List GroupZone rows. Filterable by group_id / zone_id. tags: - Zones - operationId: PlaceOS::Api::Groups::Zones_show + operationId: PlaceOS::Api::Groups::Zones_index parameters: - name: group_id - in: path - required: true + in: query schema: - type: string - format: uuid + anyOf: + - type: string + format: uuid + - type: "null" - name: zone_id - in: path - required: true + in: query + schema: + anyOf: + - type: "null" + - type: string + - name: limit + in: query + schema: + type: integer + format: Int32 + - name: offset + in: query + schema: + type: integer + format: Int32 + - name: q + in: query + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' schema: type: string + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset + schema: + anyOf: + - type: "null" + - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + post: + tags: + - Zones + operationId: PlaceOS::Api::Groups::Zones_create + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + required: true + parameters: [] + responses: + "201": + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.GroupZone' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/group_zones/{group_id}/{zone_id}: + summary: The zones a group has access to, and the permissions it has there + get: + tags: + - Zones + operationId: PlaceOS::Api::Groups::Zones_show + parameters: + - name: group_id + in: path + required: true + schema: + type: string + format: uuid + - name: zone_id + in: path + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.GroupZone' "409": description: Conflict content: @@ -21350,33 +21883,1534 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/capabilities: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. + /api/engine/v2/maps/ai/capabilities: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + get: + summary: what this domain can do, and what the caller has left of their quota + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_capabilities + parameters: [] + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.Capabilities' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/edit: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + post: + summary: ask for operations that carry out an instruction on a level's map + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_edit + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.EditParams' + required: true + parameters: [] + responses: + "202": + description: Accepted + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/jobs/{id}: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + get: + summary: 'long poll: holds until the job changes past `since`, or `wait` runs + out' + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_show_job + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + - name: wait + in: query + description: seconds to hold the request open, 0 to answer immediately + example: 25 + schema: + type: integer + format: Int32 + - name: since + in: query + description: the version the caller already has + example: 3 + schema: + anyOf: + - type: integer + format: Int32 + - type: "null" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/jobs: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + get: + summary: recent map edit jobs + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_index_jobs + parameters: + - name: mine + in: query + description: only the caller's own jobs + example: true + schema: + type: boolean + - name: zone_id + in: query + description: only jobs against this zone + example: zone-1234 + schema: + anyOf: + - type: "null" + - type: string + - name: kind + in: query + description: map_edit; another kind lists that kind instead + example: map_edit + schema: + type: string + - name: limit + in: query + schema: + type: integer + format: Int32 + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/jobs/{id}/cancel: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + post: + summary: ask a running job to stop. A call already with the vendor runs to completion. + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_cancel + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/jobs/{id}/resolve: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + post: + summary: 'record what the person did with the answer: which ops were applied + or' + description: 'record what the person did with the answer: which ops were applied + or + + rejected and why, and the upload the saved map became' + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_resolve + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.ResolveParams' + required: true + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/maps/ai/usage: + summary: AI editing of a level's SVG map, with the signage AI provider rows. + description: 'AI editing of a level''s SVG map, with the signage AI provider rows. + + + The editor posts the instruction and the context it built from the map (the + + element index, the shortlisted subtrees, the annotations and a marked up + + snapshot by upload id). The answer is a list of operations the editor + + applies, reviews and saves itself; nothing here reads or writes the map. + + One job is one vendor call, long polled through `jobs/:id` as signage is.' + get: + summary: map edit spend per provider and model + tags: + - MapAI + operationId: PlaceOS::Api::MapAI_usage + parameters: + - name: from + in: query + description: unix seconds, defaults to 30 days ago + schema: + anyOf: + - type: integer + format: Int64 + - type: "null" + - name: to + in: query + description: unix seconds, defaults to now + schema: + anyOf: + - type: integer + format: Int64 + - type: "null" + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.SignageAIJob.UsageRow' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/metadata/{name}/bulk: + summary: Metadata, named JSON documents attached to zones, systems and users (e.g. + floor maps, booking rules) + get: + summary: Fetch metadata with a specific name for multiple resources + description: 'Fetch metadata with a specific name for multiple resources + + + Allows bulk retrieval of metadata across multiple parent entities' + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_bulk_fetch + parameters: + - name: name + in: path + description: the name of the metadata key to fetch + example: settings + required: true + schema: + type: string + - name: parent_ids + in: query + description: comma-separated list of parent IDs (zones, systems, users, etc.) + example: + - zone-1 + - zone-2 + - zone-3 + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Hash-oString-nPlaceOS.Model.Metadata.Interface-pNil-c' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/metadata/{id}: + summary: Metadata, named JSON documents attached to zones, systems and users (e.g. + floor maps, booking rules) + get: + summary: Fetch metadata for a model + description: 'Fetch metadata for a model + + + Filter for a specific metadata by name via `name` param' + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_show + parameters: + - name: id + in: path + description: the parent id of the metadata to be returned + required: true + schema: + type: string + - name: name + in: query + description: the name of the metadata key + example: config + schema: + anyOf: + - type: "null" + - type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Hash-oString-nPlaceOS.Model.Metadata.Interface-c' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + put: + summary: replace the metadata with this new metadata + description: 'replace the metadata with this new metadata + + udpates are signalled on the `placeos/metadata/changed` channel' + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_update + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + required: true + parameters: + - name: id + in: path + description: the parent id of the metadata to be replaced + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + delete: + summary: remove a metadata entry from the database + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_destroy + parameters: + - name: id + in: path + description: the parent id of the metadata to be returned + required: true + schema: + type: string + - name: name + in: query + description: the name of the metadata key + example: config + required: true + schema: + type: string + responses: + "202": + description: Accepted + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + patch: + summary: update only the keys provided on the selected metadata + description: 'update only the keys provided on the selected metadata + + udpates are signalled on the `placeos/metadata/changed` channel' + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_merge + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + required: true + parameters: + - name: id + in: path + description: the parent id of the metadata to be updated + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/metadata/{id}/children: + summary: Metadata, named JSON documents attached to zones, systems and users (e.g. + floor maps, booking rules) + get: + summary: Fetch metadata for Zone children + description: 'Fetch metadata for Zone children + + + Filter for a specific metadata by name via `name` param. + + Includes the parent metadata by default via `include_parent` param.' + tags: + - Metadata + operationId: PlaceOS::Api::Metadata_children_metadata + parameters: + - name: id + in: path + description: the parent id of the metadata to be returned + required: true + schema: + type: string + - name: include_parent + in: query + description: the parent metadata is included in the results by default + example: false + schema: + type: boolean + - name: name + in: query + description: filter for a particular metadata key + example: config + schema: + anyOf: + - type: "null" + - type: string + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PlaceOS.Api.Metadata.Children' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/metadata/{id}/name: + summary: Metadata, named JSON documents attached to zones, systems and users (e.g. + floor maps, booking rules) + patch: + summary: rename a metadata field + description: 'rename a metadata field - One job is one vendor call, long polled through `jobs/:id` as signage is.' - get: - summary: what this domain can do, and what the caller has left of their quota + udpates are signalled on the `placeos/metadata/changed` channel' tags: - - MapAI - operationId: PlaceOS::Api::MapAI_capabilities - parameters: [] + - Metadata + operationId: PlaceOS::Api::Metadata_rename + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Metadata.Rename' + required: true + parameters: + - name: id + in: path + description: the parent id of the metadata to be renamed + required: true + schema: + type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.Capabilities' + $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' "409": description: Conflict content: @@ -21455,39 +23489,49 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/edit: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. - - One job is one vendor call, long polled through `jobs/:id` as signage is.' - post: - summary: ask for operations that carry out an instruction on a level's map + /api/engine/v2/metadata/{id}/history: + summary: Metadata, named JSON documents attached to zones, systems and users (e.g. + floor maps, booking rules) + get: + summary: Returns the version history for a Settings model tags: - - MapAI - operationId: PlaceOS::Api::MapAI_edit - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.EditParams' + - Metadata + operationId: PlaceOS::Api::Metadata_history + parameters: + - name: id + in: path + description: the parent id of the metadata to be returned required: true - parameters: [] + schema: + type: string + - name: name + in: query + description: the name of the metadata key + example: config + schema: + anyOf: + - type: "null" + - type: string + - name: limit + in: query + description: the maximum number of results to return + example: 10000 + schema: + type: integer + format: Int32 + - name: offset + in: query + description: the starting offset of the result set. Used to implement pagination + schema: + type: integer + format: Int32 responses: - "202": - description: Accepted + "200": + description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' + $ref: '#/components/schemas/Hash-oString-nArray-oPlaceOS.Model.Metadata.Interface-c-c' "409": description: Conflict content: @@ -21566,56 +23610,19 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/jobs/{id}: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. + /api/engine/v2/mqtt/user: + post: + summary: 'For MQTT JWT access: https://github.com/iegomez/mosquitto-go-auth#remote-mode' + description: 'For MQTT JWT access: https://github.com/iegomez/mosquitto-go-auth#remote-mode - One job is one vendor call, long polled through `jobs/:id` as signage is.' - get: - summary: 'long poll: holds until the job changes past `since`, or `wait` runs - out' + jwt_response_mode: status, jwt_params_mode: form' tags: - - MapAI - operationId: PlaceOS::Api::MapAI_show_job - parameters: - - name: id - in: path - required: true - schema: - type: string - format: uuid - - name: wait - in: query - description: seconds to hold the request open, 0 to answer immediately - example: 25 - schema: - type: integer - format: Int32 - - name: since - in: query - description: the version the caller already has - example: 3 - schema: - anyOf: - - type: integer - format: Int32 - - type: "null" + - MQTT + operationId: PlaceOS::Api::MQTT_mqtt_user + parameters: [] responses: "200": description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' "409": description: Conflict content: @@ -21694,60 +23701,38 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/jobs: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. + /api/engine/v2/mqtt/access: + post: + summary: 'Sends a form with the following params: topic, clientid, acc (1: read, + 2: write, 3: readwrite, 4: subscribe)' + description: 'Sends a form with the following params: topic, clientid, acc (1: + read, 2: write, 3: readwrite, 4: subscribe) - One job is one vendor call, long polled through `jobs/:id` as signage is.' - get: - summary: recent map edit jobs + example payload: acc=4&clientid=clientId-NwsUNfV30&topic=%2A' tags: - - MapAI - operationId: PlaceOS::Api::MapAI_index_jobs + - MQTT + operationId: PlaceOS::Api::MQTT_mqtt_access parameters: - - name: mine + - name: topic in: query - description: only the caller's own jobs - example: true + required: true schema: - type: boolean - - name: zone_id + type: string + - name: acc + in: query + description: access level required + required: true + schema: + $ref: '#/components/schemas/PlaceOS.Api.MQTT.MqttAcl' + - name: clientid in: query - description: only jobs against this zone - example: zone-1234 schema: anyOf: - type: "null" - type: string - - name: kind - in: query - description: map_edit; another kind lists that kind instead - example: map_edit - schema: - type: string - - name: limit - in: query - schema: - type: integer - format: Int32 responses: "200": description: OK - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' "409": description: Conflict content: @@ -21826,39 +23811,15 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/jobs/{id}/cancel: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. - - One job is one vendor call, long polled through `jobs/:id` as signage is.' + /api/engine/v2/notifications/google: post: - summary: ask a running job to stop. A call already with the vendor runs to completion. tags: - - MapAI - operationId: PlaceOS::Api::MapAI_cancel - parameters: - - name: id - in: path - required: true - schema: - type: string - format: uuid + - PushNotifications + operationId: PlaceOS::Api::PushNotifications_google + parameters: [] responses: "200": description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' "409": description: Conflict content: @@ -21937,50 +23898,21 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/jobs/{id}/resolve: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. - - One job is one vendor call, long polled through `jobs/:id` as signage is.' + /api/engine/v2/notifications/office365: post: - summary: 'record what the person did with the answer: which ops were applied - or' - description: 'record what the person did with the answer: which ops were applied - or - - rejected and why, and the upload the saved map became' tags: - - MapAI - operationId: PlaceOS::Api::MapAI_resolve + - PushNotifications + operationId: PlaceOS::Api::PushNotifications_microsoft requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.ResolveParams' - required: true - parameters: - - name: id - in: path + $ref: '#/components/schemas/PlaceOS.Api.MicrosoftNotification' required: true - schema: - type: string - format: uuid + parameters: [] responses: "200": description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/PlaceOS.Api.MapAI.JobResponse' "409": description: Conflict content: @@ -22059,42 +23991,60 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/maps/ai/usage: - summary: AI editing of a level's SVG map, with the signage AI provider rows. - description: 'AI editing of a level''s SVG map, with the signage AI provider rows. - - - The editor posts the instruction and the context it built from the map (the - - element index, the shortlisted subtrees, the annotations and a marked up - - snapshot by upload id). The answer is a list of operations the editor - - applies, reviews and saves itself; nothing here reads or writes the map. - - One job is one vendor call, long polled through `jobs/:id` as signage is.' + /api/engine/v2/oauth_apps: + summary: OAuth applications, the clients permitted to sign users in to PlaceOS get: - summary: map edit spend per provider and model + summary: lists the frontend applications enabled on the domains tags: - - MapAI - operationId: PlaceOS::Api::MapAI_usage + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_index parameters: - - name: from + - name: authority_id in: query - description: unix seconds, defaults to 30 days ago + description: the ID of the domain to be listed; ignored for non-admin/support + callers (forced to their own authority) + example: auth-12345 schema: anyOf: - - type: integer - format: Int64 - type: "null" - - name: to + - type: string + - name: q in: query - description: unix seconds, defaults to now + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' + schema: + type: string + - name: limit + in: query + description: the maximum number of results to return + example: 10000 + schema: + type: integer + format: UInt32 + - name: offset + in: query + description: the starting offset of the result set, used to implement pagination + schema: + type: integer + format: UInt32 + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset schema: anyOf: - - type: integer - format: Int64 - type: "null" + - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK @@ -22103,7 +24053,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Model.SignageAIJob.UsageRow' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' "409": description: Conflict content: @@ -22182,47 +24132,25 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/metadata/{name}/bulk: - summary: Metadata, named JSON documents attached to zones, systems and users (e.g. - floor maps, booking rules) - get: - summary: Fetch metadata with a specific name for multiple resources - description: 'Fetch metadata with a specific name for multiple resources - - - Allows bulk retrieval of metadata across multiple parent entities' + post: + summary: add a new user interface application tags: - - Metadata - operationId: PlaceOS::Api::Metadata_bulk_fetch - parameters: - - name: name - in: path - description: the name of the metadata key to fetch - example: settings - required: true - schema: - type: string - - name: parent_ids - in: query - description: comma-separated list of parent IDs (zones, systems, users, etc.) - example: - - zone-1 - - zone-2 - - zone-3 + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_create + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' required: true - style: form - explode: false - schema: - type: array - items: - type: string + parameters: [] responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: - $ref: '#/components/schemas/Hash-oString-nPlaceOS.Model.Metadata.Interface-pNil-c' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' "409": description: Conflict content: @@ -22301,40 +24229,26 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/metadata/{id}: - summary: Metadata, named JSON documents attached to zones, systems and users (e.g. - floor maps, booking rules) + /api/engine/v2/oauth_apps/{id}: + summary: OAuth applications, the clients permitted to sign users in to PlaceOS get: - summary: Fetch metadata for a model - description: 'Fetch metadata for a model - - - Filter for a specific metadata by name via `name` param' + summary: show the details of the applications tags: - - Metadata - operationId: PlaceOS::Api::Metadata_show + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_show parameters: - name: id in: path - description: the parent id of the metadata to be returned required: true schema: type: string - - name: name - in: query - description: the name of the metadata key - example: config - schema: - anyOf: - - type: "null" - - type: string responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/Hash-oString-nPlaceOS.Model.Metadata.Interface-c' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' "409": description: Conflict content: @@ -22414,23 +24328,19 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' put: - summary: replace the metadata with this new metadata - description: 'replace the metadata with this new metadata - - udpates are signalled on the `placeos/metadata/changed` channel' + summary: udpate an application tags: - - Metadata - operationId: PlaceOS::Api::Metadata_update + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_update requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' required: true parameters: - name: id in: path - description: the parent id of the metadata to be replaced required: true schema: type: string @@ -22440,7 +24350,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' "409": description: Conflict content: @@ -22520,21 +24430,13 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' delete: - summary: remove a metadata entry from the database + summary: remove an application tags: - - Metadata - operationId: PlaceOS::Api::Metadata_destroy + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_destroy parameters: - name: id in: path - description: the parent id of the metadata to be returned - required: true - schema: - type: string - - name: name - in: query - description: the name of the metadata key - example: config required: true schema: type: string @@ -22620,23 +24522,19 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' patch: - summary: update only the keys provided on the selected metadata - description: 'update only the keys provided on the selected metadata - - udpates are signalled on the `placeos/metadata/changed` channel' + summary: udpate an application tags: - - Metadata - operationId: PlaceOS::Api::Metadata_merge + - OAuthApplications + operationId: PlaceOS::Api::OAuthApplications_update_2 requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' required: true parameters: - name: id in: path - description: the parent id of the metadata to be updated required: true schema: type: string @@ -22646,7 +24544,99 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + "409": + description: Conflict + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "401": + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "503": + description: Service Unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "403": + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "404": + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "429": + description: Too Many Requests + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ImageGenError' + "422": + description: Unprocessable Entity + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "502": + description: Bad Gateway + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "504": + description: Gateway Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "406": + description: Not Acceptable + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + "408": + description: Request Timeout + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.CommonError' + "400": + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ParameterError' + "415": + description: Unsupported Media Type + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' + /api/engine/v2/organisations/current: + summary: 'Organisations: the customers that own domains and estate (PPT-526)' + get: + tags: + - Organisations + operationId: PlaceOS::Api::Organisations_current + parameters: [] + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Organisations.CurrentReach' "409": description: Conflict content: @@ -22725,41 +24715,60 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/metadata/{id}/children: - summary: Metadata, named JSON documents attached to zones, systems and users (e.g. - floor maps, booking rules) + /api/engine/v2/organisations: + summary: 'Organisations: the customers that own domains and estate (PPT-526)' get: - summary: Fetch metadata for Zone children - description: 'Fetch metadata for Zone children - - - Filter for a specific metadata by name via `name` param. - - Includes the parent metadata by default via `include_parent` param.' + summary: list the organisations in reach tags: - - Metadata - operationId: PlaceOS::Api::Metadata_children_metadata + - Organisations + operationId: PlaceOS::Api::Organisations_index parameters: - - name: id - in: path - description: the parent id of the metadata to be returned - required: true + - name: partner_id + in: query + description: only organisations under this partner + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" + - name: q + in: query + description: 'filters results by the given text: a record matches when any + word matches its searchable fields as a whole word, and the last word also + matches as a prefix (search as you type)' schema: type: string - - name: include_parent + - name: limit in: query - description: the parent metadata is included in the results by default - example: false + description: the maximum number of results to return + example: 10000 schema: - type: boolean - - name: name + type: integer + format: UInt32 + - name: offset in: query - description: filter for a particular metadata key - example: config + description: the starting offset of the result set, used to implement pagination + schema: + type: integer + format: UInt32 + - name: ref + in: query + description: deprecated, ignored — pagination follows the `Link` header's + offset schema: anyOf: - type: "null" - type: string + - name: fields + in: query + description: deprecated, ignored — search covers the resource's indexed fields + style: form + explode: false + schema: + type: array + items: + type: string responses: "200": description: OK @@ -22768,7 +24777,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Api.Metadata.Children' + $ref: '#/components/schemas/PlaceOS.Model.Organisation' "409": description: Conflict content: @@ -22847,37 +24856,46 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/metadata/{id}/name: - summary: Metadata, named JSON documents attached to zones, systems and users (e.g. - floor maps, booking rules) - patch: - summary: rename a metadata field - description: 'rename a metadata field + post: + summary: '`payer` and `partner_staff` are not mass-assignable, so they travel + as' + description: '`payer` and `partner_staff` are not mass-assignable, so they travel + as - udpates are signalled on the `placeos/metadata/changed` channel' + parameters' tags: - - Metadata - operationId: PlaceOS::Api::Metadata_rename + - Organisations + operationId: PlaceOS::Api::Organisations_create requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.Metadata.Rename' + $ref: '#/components/schemas/PlaceOS.Model.Organisation' required: true parameters: - - name: id - in: path - description: the parent id of the metadata to be renamed - required: true + - name: payer + in: query + description: 'who is invoiced: partner or organisation' + example: partner schema: - type: string + anyOf: + - type: "null" + - type: string + - name: partner_staff + in: query + description: true for the partner's own staff organisation + example: false + schema: + anyOf: + - type: boolean + - type: "null" responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' + $ref: '#/components/schemas/PlaceOS.Model.Organisation' "409": description: Conflict content: @@ -22956,49 +24974,26 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/metadata/{id}/history: - summary: Metadata, named JSON documents attached to zones, systems and users (e.g. - floor maps, booking rules) + /api/engine/v2/organisations/{id}: + summary: 'Organisations: the customers that own domains and estate (PPT-526)' get: - summary: Returns the version history for a Settings model tags: - - Metadata - operationId: PlaceOS::Api::Metadata_history + - Organisations + operationId: PlaceOS::Api::Organisations_show parameters: - name: id in: path - description: the parent id of the metadata to be returned required: true schema: type: string - - name: name - in: query - description: the name of the metadata key - example: config - schema: - anyOf: - - type: "null" - - type: string - - name: limit - in: query - description: the maximum number of results to return - example: 10000 - schema: - type: integer - format: Int32 - - name: offset - in: query - description: the starting offset of the result set. Used to implement pagination - schema: - type: integer - format: Int32 + format: uuid responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/Hash-oString-nArray-oPlaceOS.Model.Metadata.Interface-c-c' + $ref: '#/components/schemas/PlaceOS.Model.Organisation' "409": description: Conflict content: @@ -23077,19 +25072,46 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/mqtt/user: - post: - summary: 'For MQTT JWT access: https://github.com/iegomez/mosquitto-go-auth#remote-mode' - description: 'For MQTT JWT access: https://github.com/iegomez/mosquitto-go-auth#remote-mode - - jwt_response_mode: status, jwt_params_mode: form' + put: tags: - - MQTT - operationId: PlaceOS::Api::MQTT_mqtt_user - parameters: [] + - Organisations + operationId: PlaceOS::Api::Organisations_update + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Organisation' + required: true + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + - name: payer + in: query + description: 'who is invoiced: partner or organisation' + example: partner + schema: + anyOf: + - type: "null" + - type: string + - name: partner_staff + in: query + description: true for the partner's own staff organisation + example: false + schema: + anyOf: + - type: boolean + - type: "null" responses: "200": description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Organisation' "409": description: Conflict content: @@ -23168,38 +25190,21 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/mqtt/access: - post: - summary: 'Sends a form with the following params: topic, clientid, acc (1: read, - 2: write, 3: readwrite, 4: subscribe)' - description: 'Sends a form with the following params: topic, clientid, acc (1: - read, 2: write, 3: readwrite, 4: subscribe) - - example payload: acc=4&clientid=clientId-NwsUNfV30&topic=%2A' + delete: + summary: Deletes are RESTRICTed by the database while anything is owned tags: - - MQTT - operationId: PlaceOS::Api::MQTT_mqtt_access + - Organisations + operationId: PlaceOS::Api::Organisations_destroy parameters: - - name: topic - in: query + - name: id + in: path required: true schema: type: string - - name: acc - in: query - description: access level required - required: true - schema: - $ref: '#/components/schemas/PlaceOS.Api.MQTT.MqttAcl' - - name: clientid - in: query - schema: - anyOf: - - type: "null" - - type: string + format: uuid responses: - "200": - description: OK + "202": + description: Accepted "409": description: Conflict content: @@ -23278,15 +25283,46 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/notifications/google: - post: + patch: tags: - - PushNotifications - operationId: PlaceOS::Api::PushNotifications_google - parameters: [] + - Organisations + operationId: PlaceOS::Api::Organisations_update_2 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Organisation' + required: true + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + - name: payer + in: query + description: 'who is invoiced: partner or organisation' + example: partner + schema: + anyOf: + - type: "null" + - type: string + - name: partner_staff + in: query + description: true for the partner's own staff organisation + example: false + schema: + anyOf: + - type: boolean + - type: "null" responses: "200": description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Model.Organisation' "409": description: Conflict content: @@ -23365,21 +25401,39 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/notifications/office365: + /api/engine/v2/organisations/{id}/claim: + summary: 'Organisations: the customers that own domains and estate (PPT-526)' post: + summary: 'Assigns unowned zone trees to the organisation: the zones named, their' + description: 'Assigns unowned zone trees to the organisation: the zones named, + their + + descendants, the systems in those zones and the modules of those + + systems. Rows already owned by another organisation are left alone.' tags: - - PushNotifications - operationId: PlaceOS::Api::PushNotifications_microsoft + - Organisations + operationId: PlaceOS::Api::Organisations_claim requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Api.MicrosoftNotification' + $ref: '#/components/schemas/PlaceOS.Api.Organisations.ClaimBody' required: true - parameters: [] + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid responses: "200": description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/PlaceOS.Api.Organisations.ClaimResult' "409": description: Conflict content: @@ -23458,23 +25512,18 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/oauth_apps: - summary: OAuth applications, the clients permitted to sign users in to PlaceOS + /api/engine/v2/partners: + summary: 'Partners: integrators that bring in and manage organisations, and the' + description: 'Partners: integrators that bring in and manage organisations, and + the + + management partner that is PlaceOS itself (PPT-526)' get: - summary: lists the frontend applications enabled on the domains + summary: cluster admins list every partner; everyone else sees their own tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_index + - Partners + operationId: PlaceOS::Api::Partners_index parameters: - - name: authority_id - in: query - description: the ID of the domain to be listed; ignored for non-admin/support - callers (forced to their own authority) - example: auth-12345 - schema: - anyOf: - - type: "null" - - type: string - name: q in: query description: 'filters results by the given text: a record matches when any @@ -23520,7 +25569,7 @@ paths: schema: type: array items: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' "409": description: Conflict content: @@ -23600,15 +25649,14 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' post: - summary: add a new user interface application tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_create + - Partners + operationId: PlaceOS::Api::Partners_create requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' required: true parameters: [] responses: @@ -23617,7 +25665,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' "409": description: Conflict content: @@ -23696,26 +25744,30 @@ paths: application/json: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' - /api/engine/v2/oauth_apps/{id}: - summary: OAuth applications, the clients permitted to sign users in to PlaceOS + /api/engine/v2/partners/{id}: + summary: 'Partners: integrators that bring in and manage organisations, and the' + description: 'Partners: integrators that bring in and manage organisations, and + the + + management partner that is PlaceOS itself (PPT-526)' get: - summary: show the details of the applications tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_show + - Partners + operationId: PlaceOS::Api::Partners_show parameters: - name: id in: path required: true schema: type: string + format: uuid responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' "409": description: Conflict content: @@ -23795,15 +25847,14 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' put: - summary: udpate an application tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_update + - Partners + operationId: PlaceOS::Api::Partners_update requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' required: true parameters: - name: id @@ -23811,13 +25862,14 @@ paths: required: true schema: type: string + format: uuid responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' "409": description: Conflict content: @@ -23897,16 +25949,17 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' delete: - summary: remove an application + summary: Deletes are RESTRICTed by the database while organisations remain tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_destroy + - Partners + operationId: PlaceOS::Api::Partners_destroy parameters: - name: id in: path required: true schema: type: string + format: uuid responses: "202": description: Accepted @@ -23989,15 +26042,14 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' patch: - summary: udpate an application tags: - - OAuthApplications - operationId: PlaceOS::Api::OAuthApplications_update_2 + - Partners + operationId: PlaceOS::Api::Partners_update_2 requestBody: content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' required: true parameters: - name: id @@ -24005,13 +26057,14 @@ paths: required: true schema: type: string + format: uuid responses: "200": description: OK content: application/json: schema: - $ref: '#/components/schemas/PlaceOS.Model.DoorkeeperApplication' + $ref: '#/components/schemas/PlaceOS.Model.Partner' "409": description: Conflict content: @@ -39538,6 +41591,16 @@ paths: - Triggers operationId: PlaceOS::Api::Triggers_index parameters: + - name: organisation_id + in: query + description: only triggers bound to systems owned by this organisation; templates + are always included + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -42031,6 +44094,16 @@ paths: anyOf: - type: "null" - type: string + - name: organisation_id + in: query + description: admin users can list the users of every domain owned by this + organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -44109,6 +46182,15 @@ paths: example: true schema: type: boolean + - name: organisation_id + in: query + description: only rows owned by this organisation (must be within reach) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" - name: q in: query description: 'filters results by the given text: a record matches when any @@ -44234,7 +46316,14 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Api.Application.ContentError' post: - summary: add a new zone + summary: add a new zone. A child zone belongs to its parent's organisation; + a + description: 'add a new zone. A child zone belongs to its parent''s organisation; + a + + root zone belongs to the caller''s, or to the organisation a cluster + + admin names.' tags: - Zones operationId: PlaceOS::Api::Zones_create @@ -44244,7 +46333,16 @@ paths: schema: $ref: '#/components/schemas/PlaceOS.Model.Zone' required: true - parameters: [] + parameters: + - name: organisation_id + in: query + description: the organisation that owns a new root zone (cluster admins only) + example: 0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f + schema: + anyOf: + - type: string + format: uuid + - type: "null" responses: "201": description: Created @@ -45929,6 +48027,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" id: anyOf: - type: "null" @@ -46124,6 +48227,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" id: anyOf: - type: "null" @@ -46335,6 +48443,11 @@ components: anyOf: - type: boolean - type: "null" + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" has_runtime_error: anyOf: - type: boolean @@ -46472,6 +48585,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" timezone: anyOf: - type: object @@ -46710,6 +48828,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" place_id: anyOf: - type: "null" @@ -46843,6 +48966,11 @@ components: anyOf: - type: boolean - type: "null" + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" id: anyOf: - type: "null" @@ -46883,6 +49011,11 @@ components: - type: "null" online: type: boolean + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" x_api_key: type: string required: @@ -47034,6 +49167,72 @@ components: - total_modules - failed_modules - timestamp + PlaceOS.Model.Grant: + type: object + properties: + created_at: + anyOf: + - type: string + format: date-time + - type: "null" + updated_at: + anyOf: + - type: string + format: date-time + - type: "null" + id: + anyOf: + - type: string + format: uuid + - type: "null" + user_id: + anyOf: + - type: "null" + - type: string + scope_type: + anyOf: + - type: "null" + - type: string + scope_id: + anyOf: + - type: "null" + - type: string + permissions: + anyOf: + - type: integer + format: Int32 + - type: "null" + expires_at: + anyOf: + - type: string + format: date-time + - type: "null" + granted_by: + anyOf: + - type: "null" + - type: string + PlaceOS.Api.Grants.GrantBody: + type: object + properties: + user_id: + type: string + scope_type: + type: string + scope_id: + type: string + permissions: + type: integer + format: Int32 + expires_at: + anyOf: + - type: string + format: date-time + - type: "null" + required: + - user_id + - scope_type + - scope_id + - permissions PlaceOS.Model.Group: type: object properties: @@ -47689,6 +49888,149 @@ components: - type: string format: date-time - type: "null" + PlaceOS.Api.Organisations.CurrentReach: + type: object + properties: + reach: + type: string + enforcing: + type: boolean + organisation: + anyOf: + - type: "null" + - $ref: '#/components/schemas/PlaceOS.Model.Organisation' + partner: + anyOf: + - type: "null" + - $ref: '#/components/schemas/PlaceOS.Model.Partner' + organisations: + anyOf: + - type: "null" + - type: array + items: + $ref: '#/components/schemas/PlaceOS.Model.Organisation' + required: + - reach + - enforcing + description: 'What the caller can reach: the level, their own organisation and + partner, + + and the organisations in reach. Backoffice reads this once at login.' + PlaceOS.Model.Organisation: + type: object + properties: + created_at: + anyOf: + - type: string + format: date-time + - type: "null" + updated_at: + anyOf: + - type: string + format: date-time + - type: "null" + id: + anyOf: + - type: string + format: uuid + - type: "null" + name: + anyOf: + - type: "null" + - type: string + description: + anyOf: + - type: "null" + - type: string + payer: + anyOf: + - type: "null" + - type: string + config: + anyOf: + - type: "null" + - type: object + additionalProperties: + type: object + partner_staff: + anyOf: + - type: boolean + - type: "null" + partner_id: + anyOf: + - type: string + format: uuid + - type: "null" + PlaceOS.Api.Organisations.ClaimBody: + type: object + properties: + zone_ids: + type: array + items: + type: string + required: + - zone_ids + PlaceOS.Api.Organisations.ClaimResult: + type: object + properties: + zones: + type: integer + format: Int64 + systems: + type: integer + format: Int64 + modules: + type: integer + format: Int64 + triggers: + type: integer + format: Int64 + required: + - zones + - systems + - modules + - triggers + PlaceOS.Model.Partner: + type: object + properties: + created_at: + anyOf: + - type: string + format: date-time + - type: "null" + updated_at: + anyOf: + - type: string + format: date-time + - type: "null" + id: + anyOf: + - type: string + format: uuid + - type: "null" + name: + anyOf: + - type: "null" + - type: string + description: + anyOf: + - type: "null" + - type: string + management: + anyOf: + - type: boolean + - type: "null" + config: + anyOf: + - type: "null" + - type: object + additionalProperties: + type: object + parent_id: + anyOf: + - type: string + format: uuid + - type: "null" PlaceOS.Model.PendingMail: type: object properties: @@ -49209,6 +51551,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" control_system_id: anyOf: - type: "null" diff --git a/shard.lock b/shard.lock index a161e399..31496e8a 100644 --- a/shard.lock +++ b/shard.lock @@ -187,7 +187,7 @@ shards: pg-orm: git: https://github.com/spider-gazelle/pg-orm.git - version: 2.5.2 + version: 2.5.3 pinger: git: https://github.com/spider-gazelle/pinger.git @@ -221,9 +221,9 @@ shards: git: https://github.com/place-labs/log-backend.git version: 0.13.0 - placeos-models: + placeos-models: # Overridden git: https://github.com/placeos/models.git - version: 9.123.4 + version: 9.123.4+git.commit.b50200942c7e6bf30d999c1f500ce1375408edc0 placeos-resource: git: https://github.com/place-labs/resource.git From d1e681f9444935ea1619d3e318e78c3055ac6d95 Mon Sep 17 00:00:00 2001 From: Stephen von Takach Date: Mon, 16 Nov 2026 14:45:08 +1100 Subject: [PATCH 08/50] test: cover organisation selection boundaries --- .../organisation_auxiliary_scope_spec.cr | 92 ++++++++ .../organisation_domain_scope_spec.cr | 195 +++++++++++++++++ .../organisation_selection_spec.cr | 197 ++++++++++++++++++ spec/mcp_organisation_spec.cr | 48 +++++ spec/websocket/organisation_scope_spec.cr | 153 ++++++++++++++ 5 files changed, 685 insertions(+) create mode 100644 spec/controllers/organisation_auxiliary_scope_spec.cr create mode 100644 spec/controllers/organisation_domain_scope_spec.cr create mode 100644 spec/controllers/organisation_selection_spec.cr create mode 100644 spec/mcp_organisation_spec.cr create mode 100644 spec/websocket/organisation_scope_spec.cr diff --git a/spec/controllers/organisation_auxiliary_scope_spec.cr b/spec/controllers/organisation_auxiliary_scope_spec.cr new file mode 100644 index 00000000..92ffe6dc --- /dev/null +++ b/spec/controllers/organisation_auxiliary_scope_spec.cr @@ -0,0 +1,92 @@ +require "../helper" + +module PlaceOS::Api + describe "organisation ownership beyond estate lists" do + fixture = nil.as(Spec::Tenancy::Fixture?) + build = -> { fixture = Spec::Tenancy.build } + + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end + + it "preserves existing API keys with stored privileges above their owner's role" do + f = build.call.not_nil! + key = Model::ApiKey.new(name: "Existing #{random_name}") + key.user = f.acadian.user + key.permissions = Model::UserJWT::Permissions::Admin + secret = key.x_api_key.not_nil! + key.save! + headers = Spec::Tenancy.headers(f.acadian.user) + headers.delete("Authorization") + headers["X-API-Key"] = secret + result = client.post(Zones.base_route, headers: headers, body: {name: "Key-owned #{random_name}"}.to_json) + result.status_code.should eq 201 + JSON.parse(result.body)["organisation_id"].as_s.should eq f.acadian.organisation.id.to_s + end + + it "checks changed API key users before saving" do + f = build.call.not_nil! + key = Model::ApiKey.new(name: "Stay here #{random_name}") + key.user = f.acadian.user + key.save! + result = client.patch("#{ApiKeys.base_route}#{key.id}?organisation_id=#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {user_id: f.ntt_staff.user.id}.to_json) + result.status_code.should eq 404 + Model::ApiKey.find!(key.id.as(String)).user_id.should eq f.acadian.user.id + end + + it "checks changed OAuth owners before saving" do + f = build.call.not_nil! + app = Model::Generator.doorkeeper_application(owner: f.acadian.authority).save! + result = client.patch("#{OAuthApplications.base_route}#{app.id}?organisation_id=#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {owner_id: f.ntt_staff.authority.id}.to_json) + result.status_code.should eq 404 + Model::DoorkeeperApplication.find!(app.id.not_nil!).owner_id.should eq f.acadian.authority.id + end + + it "filters metadata children individually when a legacy tree crosses organisations" do + f = build.call.not_nil! + f.ntt_staff.building.parent_id = f.acadian.org_zone.id + f.ntt_staff.building.save! + result = client.get("#{Metadata.base_route}/#{f.acadian.org_zone.id}/children?organisation_id=#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)) + result.status_code.should eq 200 + ids = JSON.parse(result.body).as_a.map(&.["zone"]["id"].as_s) + ids.should contain(f.acadian.building.id) + ids.should_not contain(f.ntt_staff.building.id) + end + + it "keeps organisation history available and hides sibling changes" do + f = build.call.not_nil! + result = client.get("#{History.base_route}?resource_types=zone", headers: Spec::Tenancy.headers(f.acadian.admin)) + result.status_code.should eq 200 + ids = JSON.parse(result.body).as_a.map(&.["resource_id"].as_s) + ids.should contain(f.acadian.building.id) + ids.should_not contain(f.ntt_staff.building.id) + end + + it "scopes deleted history and restoration using the recorded owner" do + f = build.call.not_nil! + zone = Model::Generator.zone.tap { |z| z.name = "Deleted #{random_name}"; z.organisation_id = f.acadian.organisation.id }.save! + id = zone.id.as(String) + zone.destroy + suffix = "organisation_id=#{f.acadian.organisation.id}" + result = client.get("#{History.base_route}?resource_id=#{id}&#{suffix}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)) + result.status_code.should eq 200 + JSON.parse(result.body).as_a.map(&.["action"].as_s).should contain("delete") + restored = client.post("#{History.base_route}undelete?resource_type=zone&resource_id=#{id}&#{suffix}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)) + restored.status_code.should eq 201 + Model::Zone.find!(id).organisation_id.should eq f.acadian.organisation.id + end + + it "refuses unrestricted Flux for organisation users before contacting Influx" do + f = build.call.not_nil! + headers = Spec::Tenancy.headers(f.acadian.admin) + headers["Content-Type"] = "application/vnd.flux" + result = client.post("#{Flux.base_route.rstrip('/')}/query", headers: headers, body: "from(bucket: \"place\") |> range(start: -1m)") + result.status_code.should eq 403 + end + end +end diff --git a/spec/controllers/organisation_domain_scope_spec.cr b/spec/controllers/organisation_domain_scope_spec.cr new file mode 100644 index 00000000..96b8c1a9 --- /dev/null +++ b/spec/controllers/organisation_domain_scope_spec.cr @@ -0,0 +1,195 @@ +require "../helper" + +private def domain_scope_get(path, user) + client.get(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user)) +end + +module PlaceOS::Api + describe "organisation-selected domain resources" do + fixture = nil.as(Spec::Tenancy::Fixture?) + build = -> { fixture = Spec::Tenancy.build } + global_storages = [] of String + + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + unless global_storages.empty? + Model::Upload.where(storage_id: global_storages).delete_all + Model::Storage.where(id: global_storages).delete_all + global_storages.clear + end + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end + + it "preserves ordinary callers' domain-owned lists without a selector" do + f = build.call.not_nil! + own = Model::Generator.asset_category(f.acadian.authority).save! + foreign = Model::Generator.asset_category(f.ucla.authority).save! + result = domain_scope_get("#{AssetCategories.base_route}?limit=500", f.acadian.admin) + result.status_code.should eq 200 + ids = Spec::Tenancy.ids(result.body) + ids.should contain(own.id) + ids.should_not contain(foreign.id) + end + + it "lists and reads the selected customer's categories using the partner's unchanged token and Host" do + f = build.call.not_nil! + target = Model::Generator.asset_category(f.acadian.authority).save! + home = Model::Generator.asset_category(f.ntt_staff.authority).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + result = domain_scope_get("#{AssetCategories.base_route}#{suffix}", f.ntt_staff.admin) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should contain(target.id) + Spec::Tenancy.ids(result.body).should_not contain(home.id) + domain_scope_get("#{AssetCategories.base_route}#{target.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 200 + domain_scope_get("#{AssetCategories.base_route}#{home.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 404 + end + + it "creates categories under the selected organisation's authority" do + f = build.call.not_nil! + result = client.post("#{AssetCategories.base_route}?organisation_id=#{f.acadian.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {name: "Selected category #{random_name}"}.to_json) + result.status_code.should eq 201 + JSON.parse(result.body)["authority_id"].as_s.should eq f.acadian.authority.id + end + + it "refuses a category parent from a different selected organisation on update" do + f = build.call.not_nil! + home = Model::Generator.asset_category(f.ntt_staff.authority).save! + target = Model::Generator.asset_category(f.acadian.authority).save! + result = client.patch("#{AssetCategories.base_route}#{home.id}?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {parent_category_id: target.id}.to_json) + result.status_code.should eq 404 + Model::AssetCategory.find!(home.id.as(String)).parent_category_id.should be_nil + end + + it "rechecks a changed asset type's category against the selection" do + f = build.call.not_nil! + home = Model::Generator.asset_category(f.ntt_staff.authority).save! + target = Model::Generator.asset_category(f.acadian.authority).save! + type = Model::Generator.asset_type(home).save! + result = client.patch("#{AssetTypes.base_route}#{type.id}?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {category_id: target.id}.to_json) + result.status_code.should eq 404 + Model::AssetType.find!(type.id.as(String)).category_id.should eq home.id + end + + it "lists groups in the selected domain and conceals sibling group ids" do + f = build.call.not_nil! + target = Model::Generator.group(authority: f.acadian.authority).save! + home = Model::Generator.group(authority: f.ntt_staff.authority).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + result = domain_scope_get("#{Groups.base_route}#{suffix}", f.ntt_staff.admin) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should contain(target.id.to_s) + Spec::Tenancy.ids(result.body).should_not contain(home.id.to_s) + domain_scope_get("#{Groups.base_route}#{home.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 404 + end + + it "reads the selected customer's signage playlist" do + f = build.call.not_nil! + target = Model::Generator.playlist(authority: f.acadian.authority).save! + result = domain_scope_get("#{Playlist.base_route}/#{target.id}?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin) + result.status_code.should eq 200 + JSON.parse(result.body)["id"].as_s.should eq target.id + end + + it "scopes dashboards and alerts for partner administrators to the selection" do + f = build.call.not_nil! + home_dashboard = Model::Generator.alert_dashboard(authority_id: f.ntt_staff.authority.id).save! + target_dashboard = Model::Generator.alert_dashboard(authority_id: f.acadian.authority.id).save! + home_alert = Model::Generator.alert(alert_dashboard_id: home_dashboard.id).save! + target_alert = Model::Generator.alert(alert_dashboard_id: target_dashboard.id).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + dashboards = domain_scope_get("#{AlertDashboards.base_route}#{suffix}", f.ntt_staff.admin) + dashboards.status_code.should eq 200 + Spec::Tenancy.ids(dashboards.body).should contain(target_dashboard.id) + Spec::Tenancy.ids(dashboards.body).should_not contain(home_dashboard.id) + alerts = domain_scope_get("#{Alerts.base_route}#{suffix}", f.ntt_staff.admin) + alerts.status_code.should eq 200 + Spec::Tenancy.ids(alerts.body).should contain(target_alert.id) + Spec::Tenancy.ids(alerts.body).should_not contain(home_alert.id) + domain_scope_get("#{Alerts.base_route}#{home_alert.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 404 + end + + it "rechecks a changed alert dashboard reference" do + f = build.call.not_nil! + home = Model::Generator.alert_dashboard(authority_id: f.ntt_staff.authority.id).save! + target = Model::Generator.alert_dashboard(authority_id: f.acadian.authority.id).save! + alert = Model::Generator.alert(alert_dashboard_id: home.id).save! + result = client.patch("#{Alerts.base_route}#{alert.id}?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {alert_dashboard_id: target.id}.to_json) + result.status_code.should eq 404 + Model::Alert.find!(alert.id.as(String)).alert_dashboard_id.should eq home.id + end + + it "conceals storage ids from a sibling organisation" do + f = build.call.not_nil! + home = Model::Generator.storage(authority_id: f.ntt_staff.authority.id).save! + result = domain_scope_get("#{Storages.base_route}/#{home.id}?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin) + result.status_code.should eq 404 + end + + it "rejects moving storage ownership through a changed authority reference" do + f = build.call.not_nil! + home = Model::Generator.storage(authority_id: f.ntt_staff.authority.id).save! + result = client.patch("#{Storages.base_route}/#{home.id}?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: {authority_id: f.acadian.authority.id}.to_json) + result.status_code.should eq 404 + Model::Storage.find!(home.id.as(String)).authority_id.should eq f.ntt_staff.authority.id + end + + it "refuses signing another organisation's upload even for partner administrators" do + f = build.call.not_nil! + storage = Model::Generator.storage(authority_id: f.ntt_staff.authority.id).save! + upload = Model::Generator.upload(f.ntt_staff.admin, storage.id).save! + result = domain_scope_get("#{Uploads.base_route}/#{upload.id}/url?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin) + result.status_code.should eq 404 + end + + it "lists uploads in the selected domain's storage" do + f = build.call.not_nil! + home_storage = Model::Generator.storage(authority_id: f.ntt_staff.authority.id).save! + target_storage = Model::Generator.storage(authority_id: f.acadian.authority.id).save! + home = Model::Generator.upload(f.ntt_staff.admin, home_storage.id).save! + target = Model::Generator.upload(f.acadian.admin, target_storage.id).save! + result = domain_scope_get("#{Uploads.base_route}?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should contain(target.id) + Spec::Tenancy.ids(result.body).should_not contain(home.id) + end + + it "records immutable upload authority on shared storage and never resumes another selected organisation's upload" do + f = build.call.not_nil! + storage = Model::Generator.storage.save! + global_storages << storage.id.as(String) + payload = {file_name: "shared-#{random_name}.png", file_size: 50, file_id: "checksum", file_mime: "image/png"}.to_json + first = client.post("#{Uploads.base_route}?organisation_id=#{f.acadian.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: payload) + first.status_code.should eq 200 + first_id = JSON.parse(first.body)["upload_id"].as_s + upload = Model::Upload.find!(first_id) + upload.object_options["authority_id"]?.try(&.as_s).should eq f.acadian.authority.id + upload.object_key.should start_with("/#{f.acadian.authority.domain}/") + second = client.post("#{Uploads.base_route}?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: payload) + second.status_code.should eq 200 + JSON.parse(second.body)["upload_id"].as_s.should_not eq first_id + end + + it "requires an explicit domain when a selected foreign organisation has several authorities" do + f = build.call.not_nil! + extra = Model::Generator.authority("second.acadian.test").tap(&.organisation_id = f.acadian.organisation.id).save! + base = "#{AssetCategories.base_route}?organisation_id=#{f.acadian.organisation.id}" + body = {name: "Ambiguous #{random_name}"}.to_json + ambiguous = client.post(base, headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: body) + ambiguous.status_code.should eq 400 + result = client.post("#{base}&authority_id=#{extra.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: body) + result.status_code.should eq 201 + JSON.parse(result.body)["authority_id"].as_s.should eq extra.id + end + end +end diff --git a/spec/controllers/organisation_selection_spec.cr b/spec/controllers/organisation_selection_spec.cr new file mode 100644 index 00000000..0d826a12 --- /dev/null +++ b/spec/controllers/organisation_selection_spec.cr @@ -0,0 +1,197 @@ +require "../helper" + +private def selection_get(path, user) + client.get(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user)) +end + +private def selection_patch(path, user, body) + client.patch(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user), body: body.to_json) +end + +private def selection_post(path, user, body) + client.post(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user), body: body.to_json) +end + +module PlaceOS::Api + describe "request organisation selection" do + fixture = nil.as(Spec::Tenancy::Fixture?) + build = -> { fixture = Spec::Tenancy.build } + + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end + + it "keeps unchanged requests in the ordinary caller's home organisation when grants add reach" do + f = build.call.not_nil! + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s).save! + + result = selection_get("#{Zones.base_route}?limit=500", f.ucla.admin) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).sort.should eq [f.ucla.org_zone.id.as(String), f.ucla.building.id.as(String)].sort + selection_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + selection_get("#{Zones.base_route}#{f.acadian.org_zone.id}?organisation_id=#{f.acadian.organisation.id}", f.ucla.admin).status_code.should eq 200 + end + + it "keeps single-organisation request payloads and write ownership unchanged" do + f = build.call.not_nil! + result = selection_post(Zones.base_route, f.acadian.admin, {name: "Unchanged #{random_name}"}) + result.status_code.should eq 201 + JSON.parse(result.body)["organisation_id"].as_s.should eq f.acadian.organisation.id.to_s + selection_get("#{Zones.base_route}#{f.acadian.building.id}", f.acadian.admin).status_code.should eq 200 + end + + it "requires partner staff to select an organisation for estate lists and details" do + f = build.call.not_nil! + [Zones.base_route, "#{Zones.base_route}#{f.acadian.org_zone.id}", Systems.base_route, Modules.base_route].each do |path| + result = selection_get(path, f.ntt_staff.admin) + result.status_code.should eq 400 + JSON.parse(result.body)["code"].as_s.should eq "organisation_required" + end + end + + it "requires management staff to select an organisation for estate requests" do + f = build.call.not_nil! + result = selection_get(Zones.base_route, f.placeos.admin) + result.status_code.should eq 400 + JSON.parse(result.body)["code"].as_s.should eq "organisation_required" + selection_get(Brokers.base_route, f.placeos.admin).status_code.should eq 200 + selection_get("#{Organisations.base_route}current", f.placeos.admin).status_code.should eq 200 + end + + it "rejects malformed, duplicate and inaccessible selectors consistently" do + f = build.call.not_nil! + base = "#{Zones.base_route}#{f.acadian.org_zone.id}" + selection_get("#{base}?organisation_id=not-a-uuid", f.ntt_staff.admin).status_code.should eq 400 + selection_get("#{base}?organisation_id=#{f.acadian.organisation.id}&organisation_id=#{f.ntt_staff.organisation.id}", f.ntt_staff.admin).status_code.should eq 400 + selection_get("#{base}?organisation_id=#{UUID.random}", f.ntt_staff.admin).status_code.should eq 404 + selection_get("#{base}?organisation_id=#{f.ucla.organisation.id}", f.ntt_staff.admin).status_code.should eq 404 + end + + it "does not permit a selected sibling organisation's direct ids, updates or deletes" do + f = build.call.not_nil! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + selection_get("#{Zones.base_route}#{f.ntt_staff.building.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 404 + selection_patch("#{Zones.base_route}#{f.ntt_staff.building.id}#{suffix}", f.ntt_staff.admin, {name: "Not changed"}).status_code.should eq 404 + client.delete("#{Zones.base_route}#{f.ntt_staff.building.id}#{suffix}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)).status_code.should eq 404 + Model::Zone.find!(f.ntt_staff.building.id.as(String)).name.should eq f.ntt_staff.building.name + end + + it "owns new rows through the selection and refuses a sibling parent" do + f = build.call.not_nil! + path = "#{Zones.base_route}?organisation_id=#{f.acadian.organisation.id}" + result = selection_post(path, f.ntt_staff.admin, {name: "Selected #{random_name}"}) + result.status_code.should eq 201 + JSON.parse(result.body)["organisation_id"].as_s.should eq f.acadian.organisation.id.to_s + selection_post(path, f.ntt_staff.admin, {name: "Wrong parent #{random_name}", parent_id: f.ntt_staff.building.id}).status_code.should eq 404 + end + + it "rejects sibling systems supplied with a selected organisation to modules index" do + f = build.call.not_nil! + result = selection_get("#{Modules.base_route}?organisation_id=#{f.acadian.organisation.id}&control_system_id=#{f.ntt_staff.system.id}", f.ntt_staff.admin) + result.status_code.should eq 404 + end + + it "rejects sibling authorities supplied with a selected organisation to users index" do + f = build.call.not_nil! + result = selection_get("#{Users.base_route}?organisation_id=#{f.acadian.organisation.id}&authority_id=#{f.ntt_staff.authority.id}", f.ntt_staff.admin) + result.status_code.should eq 404 + end + + it "limits aggregate tags to the selected organisation" do + f = build.call.not_nil! + f.acadian.building.tags = Set{"building", "selected-only"} + f.acadian.building.save! + f.ntt_staff.building.tags = Set{"building", "sibling-only"} + f.ntt_staff.building.save! + result = selection_get("#{Zones.base_route}tags?organisation_id=#{f.acadian.organisation.id}", f.ntt_staff.admin) + result.status_code.should eq 200 + result.body.should contain("selected-only") + result.body.should_not contain("sibling-only") + end + + it "allows ordinary callers to discover accessible organisations without exposing config or billing" do + f = build.call.not_nil! + f.ucla.organisation.config = {"private" => JSON::Any.new("not a selector field")} + f.ucla.organisation.save! + Model::Generator.grant(f.ucla.user, "organisation", f.acadian.organisation.id.to_s).save! + result = selection_get("#{Organisations.base_route}?limit=500", f.ucla.user) + result.status_code.should eq 200 + organisations = JSON.parse(result.body).as_a + organisations.map(&.["id"].as_s).sort.should eq [f.ucla.organisation.id.to_s, f.acadian.organisation.id.to_s].sort + organisations.each do |organisation| + organisation["config"]?.should be_nil + organisation["payer"]?.should be_nil + end + current = selection_get("#{Organisations.base_route}current", f.ucla.user) + current.status_code.should eq 200 + discovery = JSON.parse(current.body) + discovery["organisation"]["config"]?.should be_nil + discovery["organisation"]["payer"]?.should be_nil + discovery["organisations"].as_a.each do |organisation| + organisation["config"]?.should be_nil + organisation["payer"]?.should be_nil + end + end + + it "keeps management-partner customer administrators in their own organisation" do + f = build.call.not_nil! + customer = Spec::Tenancy.org("managed.test", Model::Generator.organisation(partner: f.management).save!) + result = selection_get("#{Organisations.base_route}current", customer.admin) + result.status_code.should eq 200 + JSON.parse(result.body)["reach"].as_s.should eq "organisation" + selection_get("#{Zones.base_route}#{f.ucla.building.id}?organisation_id=#{f.ucla.organisation.id}", customer.admin).status_code.should eq 404 + selection_get(Brokers.base_route, customer.admin).status_code.should eq 403 + end + + it "does not turn a read grant into write access using the home administrator flag" do + f = build.call.not_nil! + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, Model::Permissions::Read).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + selection_get("#{Zones.base_route}#{f.acadian.building.id}#{suffix}", f.ucla.admin).status_code.should eq 200 + selection_patch("#{Zones.base_route}#{f.acadian.building.id}#{suffix}", f.ucla.admin, {name: "Read must not write"}).status_code.should eq 403 + selection_post("#{Zones.base_route}#{suffix}", f.ucla.admin, {name: "Read must not create #{random_name}"}).status_code.should eq 403 + client.delete("#{Zones.base_route}#{f.acadian.building.id}#{suffix}", headers: Spec::Tenancy.headers(f.ucla.admin)).status_code.should eq 403 + end + + it "preserves the exact authority boundary of a read grant within a multi-domain organisation" do + f = build.call.not_nil! + other_authority = Model::Generator.authority("other.acadian.test") + other_authority.organisation_id = f.acadian.organisation.id + other_authority.save! + other_user = Model::Generator.user(other_authority).save! + Model::Generator.grant(f.ucla.admin, "authority", f.acadian.authority.id.as(String), Model::Permissions::Read).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + + result = selection_get("#{Users.base_route}#{suffix}", f.ucla.admin) + result.status_code.should eq 200 + ids = Spec::Tenancy.ids(result.body) + ids.should contain(f.acadian.user.id) + ids.should_not contain(other_user.id) + selection_get("#{Users.base_route}#{other_user.id}#{suffix}", f.ucla.admin).status_code.should eq 404 + selection_get("#{Domains.base_route}#{other_authority.id}#{suffix}", f.ucla.admin).status_code.should eq 404 + end + + it "rejects revoked and expired grant selections on subsequent requests" do + f = build.call.not_nil! + grant = Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s).save! + path = "#{Zones.base_route}#{f.acadian.building.id}?organisation_id=#{f.acadian.organisation.id}" + selection_get(path, f.ucla.admin).status_code.should eq 200 + grant.destroy + selection_get(path, f.ucla.admin).status_code.should eq 404 + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, expires_at: 1.minute.ago).save! + selection_get(path, f.ucla.admin).status_code.should eq 404 + end + + it "retains legacy request behaviour when enforcement is disabled" do + f = build.call.not_nil! + Utils::Tenancy.enforce = false + selection_get(Zones.base_route, f.ntt_staff.admin).status_code.should eq 200 + selection_get("#{Zones.base_route}#{f.ucla.building.id}", f.acadian.admin).status_code.should eq 200 + end + end +end diff --git a/spec/mcp_organisation_spec.cr b/spec/mcp_organisation_spec.cr new file mode 100644 index 00000000..4c771a7b --- /dev/null +++ b/spec/mcp_organisation_spec.cr @@ -0,0 +1,48 @@ +require "./helper" + +module PlaceOS::Api + describe "organisation selection through MCP" do + router = ActionController::SpecHelper.new + MCP.mount(router) + mcp_client = router.hot_topic + fixture = nil.as(Spec::Tenancy::Fixture?) + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end + + it "declares organisation selection on detail tools and resource templates" do + description = ActionController::MCPServer.generate_description + _, show = description.tool?("zones_show").not_nil! + show.params.map(&.name).should contain "organisation_id" + resources = description.toolboxes.flat_map(&.tools).compact_map(&.resource) + resources.select(&.includes?("/state")).each do |template| + template.should contain "organisation_id" + end + resources.find!(&.includes?("/logs")).should contain "organisation_id" + end + + it "passes the selected organisation through tool calls instead of using full partner reach" do + f = fixture = Spec::Tenancy.build + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + headers["Accept"] = "application/json" + body = { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "zones_show", + arguments: {id: f.ntt_staff.org_zone.id, organisation_id: f.acadian.organisation.id.to_s}, + }, + } + response = mcp_client.post(MCP::PATH, headers: headers, body: body.to_json) + response.status_code.should eq 200 + result = JSON.parse(response.body)["result"] + result["isError"].as_bool.should be_true + end + end +end diff --git a/spec/websocket/organisation_scope_spec.cr b/spec/websocket/organisation_scope_spec.cr new file mode 100644 index 00000000..5ebbf5fb --- /dev/null +++ b/spec/websocket/organisation_scope_spec.cr @@ -0,0 +1,153 @@ +require "../helper" + +module PlaceOS::Api::WebSocket + private def self.scoped_socket(user : Model::User, organisation_id : UUID, scopes : Array(Model::UserJWT::Scope)? = nil, &) + credentials = Spec::Tenancy.headers(user) + bearer = credentials["Authorization"].split(' ').last + if scopes + token = Model::UserJWT.decode(bearer) + bearer = Model::UserJWT.new(iss: token.iss, iat: token.iat, exp: token.exp, domain: token.domain, id: token.id, user: token.user, scope: scopes).encode + end + path = "#{Systems.base_route}control?bearer_token=#{bearer}&organisation_id=#{organisation_id}" + socket = client.establish_ws(path, headers: HTTP::Headers{"Host" => credentials["Host"]}) + responses = Channel(Session::Response).new(32) + socket.on_message do |message| + responses.send(Session::Response.from_json(message)) unless message == "pong" + end + spawn { socket.run } + yield socket, responses + ensure + socket.try &.close + end + + private def self.scope_response(responses : Channel(Session::Response), request_id : Int64) : Session::Response + loop do + select + when response = responses.receive + return response if response.id == request_id && !response.type.notify? + when timeout(5.seconds) + raise "timed out waiting for socket response #{request_id}" + end + end + end + + private def self.scope_request(id : Int64, system : Model::ControlSystem, mod : String, command : Session::Request::Command, name : String = "scope_test") + Session::Request.new(id: id, system_id: system.id.as(String), module_name: mod, command: command, name: name) + end + + describe "organisation-scoped websocket sessions" do + fixture = nil.as(Spec::Tenancy::Fixture?) + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + Spec::Tenancy.teardown(f) + fixture = nil + end + end + + it "keeps a selected customer separate from another reachable organisation" do + f = fixture = Spec::Tenancy.build + scoped_socket(f.ntt_staff.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(1_i64, f.ntt_staff.system, f.ntt_staff.mod.resolved_name, :bind).to_json + response = scope_response(responses, 1_i64) + response.type.should eq Session::Response::Type::Error + response.error_code.should eq Session::Response::ErrorCode::ModuleNotFound + end + end + + it "refuses a foreign module id paired with a system in the selected organisation" do + f = fixture = Spec::Tenancy.build + scoped_socket(f.ntt_staff.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(2_i64, f.acadian.system, f.ntt_staff.mod.id.as(String), :debug).to_json + response = scope_response(responses, 2_i64) + response.type.should eq Session::Response::Type::Error + response.error_code.should eq Session::Response::ErrorCode::AccessDenied + end + end + + it "does not expose a foreign module referenced by a selected system" do + f = fixture = Spec::Tenancy.build + f.acadian.system.modules = [f.ntt_staff.mod.id.as(String)] + f.acadian.system.save! + scoped_socket(f.ntt_staff.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(9_i64, f.acadian.system, f.ntt_staff.mod.resolved_name, :bind).to_json + response = scope_response(responses, 9_i64) + response.type.should eq Session::Response::Type::Error + response.error_code.should eq Session::Response::ErrorCode::ModuleNotFound + end + end + + it "rechecks grants on an already open socket" do + f = fixture = Spec::Tenancy.build + grant = Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: Model::Permissions::Read.to_i).save! + scoped_socket(f.ucla.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(3_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind).to_json + scope_response(responses, 3_i64).type.should eq Session::Response::Type::Success + grant.destroy + socket.send scope_request(4_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind, "after_revoke").to_json + response = scope_response(responses, 4_i64) + response.type.should eq Session::Response::Type::Error + response.error_code.should eq Session::Response::ErrorCode::AccessDenied + end + end + + it "allows read-only OAuth scopes to bind while refusing execution on the same socket" do + f = fixture = Spec::Tenancy.build + scopes = [Model::UserJWT::Scope.new("control", Model::UserJWT::Scope::Access::Read)] + scoped_socket(f.acadian.admin, f.acadian.organisation.id.as(UUID), scopes) do |socket, responses| + socket.send scope_request(6_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind).to_json + scope_response(responses, 6_i64).type.should eq Session::Response::Type::Success + socket.send scope_request(7_i64, f.acadian.system, f.acadian.mod.resolved_name, :exec).to_json + response = scope_response(responses, 7_i64) + response.error_code.should eq Session::Response::ErrorCode::AccessDenied + response.response_code.should eq 403 + end + end + + it "stops an existing subscription from delivering state after its grant is revoked" do + f = fixture = Spec::Tenancy.build + grant = Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: Model::Permissions::Read.to_i).save! + wait_for_module_lookups(f.acadian.system.id.as(String), {"#{f.acadian.mod.resolved_name}/1" => f.acadian.mod.id.as(String)}) + scoped_socket(f.ucla.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(8_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind, "live_scope").to_json + scope_response(responses, 8_i64).type.should eq Session::Response::Type::Success + storage = PlaceOS::Driver::RedisStorage.new(f.acadian.mod.id.as(String)) + storage["live_scope"] = 100 + loop do + select + when response = responses.receive + break if response.type.notify? && response.value == "100" + when timeout(5.seconds) + raise "initial authorised state notification was not delivered" + end + end + grant.destroy + storage["live_scope"] = 200 + deadline = Time.monotonic + 500.milliseconds + loop do + remaining = deadline - Time.monotonic + break if remaining <= Time::Span.zero + select + when response = responses.receive + response.value.should_not eq "200" + when timeout(remaining) + break + end + end + end + end + + it "does not turn a read grant into execution through the caller's home admin flag" do + f = fixture = Spec::Tenancy.build + Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: Model::Permissions::Read.to_i).save! + scoped_socket(f.ucla.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| + socket.send scope_request(5_i64, f.acadian.system, f.acadian.mod.resolved_name, :exec, "scope_test").to_json + response = scope_response(responses, 5_i64) + response.type.should eq Session::Response::Type::Error + response.error_code.should eq Session::Response::ErrorCode::AccessDenied + response.response_code.should eq 403 + end + end + end +end From 8fd2f1ff391fd1c5765dab80e660eed4b1578294 Mon Sep 17 00:00:00 2001 From: Stephen von Takach Date: Mon, 16 Nov 2026 15:44:02 +1100 Subject: [PATCH 09/50] feat: scope REST requests to a selected organisation --- .../organisation_auxiliary_scope_spec.cr | 126 +++++++ .../organisation_domain_scope_spec.cr | 67 ++++ .../organisation_mqtt_scope_spec.cr | 112 ++++++ .../organisation_multi_domain_scope_spec.cr | 207 +++++++++++ .../organisation_selection_spec.cr | 50 ++- spec/controllers/tenancy_spec.cr | 55 +-- spec/mcp_resources_spec.cr | 8 +- spec/module_logs_spec.cr | 46 +++ spec/webrtc/organisation_scope_spec.cr | 101 +++++ spec/websocket/organisation_scope_spec.cr | 30 +- .../controllers/alert_dashboards.cr | 20 +- src/placeos-rest-api/controllers/alerts.cr | 27 +- src/placeos-rest-api/controllers/api_keys.cr | 14 +- .../controllers/application.cr | 22 ++ .../controllers/asset_categories.cr | 26 +- .../controllers/asset_purchase_orders.cr | 9 +- .../controllers/asset_types.cr | 21 +- src/placeos-rest-api/controllers/assets.cr | 72 ++-- .../controllers/authentications.cr | 11 +- src/placeos-rest-api/controllers/chat_gpt.cr | 14 +- .../controllers/chat_gpt/plugins.cr | 3 +- src/placeos-rest-api/controllers/domains.cr | 52 ++- src/placeos-rest-api/controllers/edges.cr | 4 + src/placeos-rest-api/controllers/flux.cr | 1 + src/placeos-rest-api/controllers/grants.cr | 4 +- src/placeos-rest-api/controllers/groups.cr | 29 +- .../controllers/groups/history.cr | 10 +- .../controllers/groups/invitation.cr | 7 +- .../controllers/groups/user.cr | 15 +- .../controllers/groups/zone.cr | 17 +- src/placeos-rest-api/controllers/history.cr | 105 +++++- src/placeos-rest-api/controllers/map_ai.cr | 3 +- src/placeos-rest-api/controllers/metadata.cr | 27 +- src/placeos-rest-api/controllers/modules.cr | 31 +- .../controllers/oauth_applications.cr | 18 +- .../controllers/organisations.cr | 75 +++- src/placeos-rest-api/controllers/partners.cr | 6 +- .../controllers/pending_mails.cr | 13 +- .../controllers/public_events.cr | 8 + src/placeos-rest-api/controllers/root.cr | 9 +- src/placeos-rest-api/controllers/settings.cr | 3 +- src/placeos-rest-api/controllers/short_url.cr | 9 +- src/placeos-rest-api/controllers/signage.cr | 35 +- .../controllers/signage/ai.cr | 20 +- .../controllers/signage/ai_providers.cr | 9 +- .../controllers/signage/playlist_media.cr | 19 +- .../controllers/signage/playlists.cr | 6 +- .../controllers/signage/plugins.cr | 12 +- .../controllers/signage/template_mappings.cr | 7 +- .../controllers/signage/templates.cr | 6 +- src/placeos-rest-api/controllers/storages.cr | 28 +- src/placeos-rest-api/controllers/systems.cr | 38 +- .../controllers/tenant_consent.cr | 3 + src/placeos-rest-api/controllers/triggers.cr | 20 +- src/placeos-rest-api/controllers/uploads.cr | 71 +++- src/placeos-rest-api/controllers/users.cr | 44 ++- src/placeos-rest-api/controllers/webhook.cr | 5 + src/placeos-rest-api/controllers/zones.cr | 4 +- src/placeos-rest-api/error.cr | 8 + src/placeos-rest-api/mcp.cr | 9 +- .../utilities/group_permissions.cr | 15 +- .../utilities/history_scope.cr | 101 +++++ .../utilities/image_gen/store.cr | 1 + src/placeos-rest-api/utilities/module_logs.cr | 42 ++- .../utilities/object_store.cr | 6 +- .../utilities/resource_authority.cr | 83 +++++ src/placeos-rest-api/utilities/tenancy.cr | 351 ++++++++++-------- .../utilities/tenancy_policy.cr | 173 +++++++++ src/placeos-rest-api/websocket/manager.cr | 12 +- src/placeos-rest-api/websocket/session.cr | 204 ++++++++-- 70 files changed, 2381 insertions(+), 438 deletions(-) create mode 100644 spec/controllers/organisation_mqtt_scope_spec.cr create mode 100644 spec/controllers/organisation_multi_domain_scope_spec.cr create mode 100644 spec/webrtc/organisation_scope_spec.cr create mode 100644 src/placeos-rest-api/utilities/history_scope.cr create mode 100644 src/placeos-rest-api/utilities/resource_authority.cr create mode 100644 src/placeos-rest-api/utilities/tenancy_policy.cr diff --git a/spec/controllers/organisation_auxiliary_scope_spec.cr b/spec/controllers/organisation_auxiliary_scope_spec.cr index 92ffe6dc..1bfe90b8 100644 --- a/spec/controllers/organisation_auxiliary_scope_spec.cr +++ b/spec/controllers/organisation_auxiliary_scope_spec.cr @@ -29,6 +29,132 @@ module PlaceOS::Api JSON.parse(result.body)["organisation_id"].as_s.should eq f.acadian.organisation.id.to_s end + it "requires Manage before a foreign creation grant can mint an administrator API key" do + f = build.call.not_nil! + grant = Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, + Model::Permissions::Read | Model::Permissions::Create).save! + name = "Delegated credential #{random_name}" + path = "#{ApiKeys.base_route}?organisation_id=#{f.acadian.organisation.id}" + body = {name: name, user_id: f.acadian.user.id, permissions: Model::UserJWT::Permissions::Admin.value}.to_json + headers = Spec::Tenancy.headers(f.ucla.admin) + + denied = client.post(path, headers: headers, body: body) + denied.status_code.should eq 403 + Model::ApiKey.where(name: name).count.should eq 0 + + grant.permission_flags |= Model::Permissions::Manage + grant.save! + allowed = client.post(path, headers: headers, body: body) + allowed.status_code.should eq 201 + key = Model::ApiKey.find!(JSON.parse(allowed.body)["id"].as_s) + key.authority_id.should eq f.acadian.authority.id + key.permissions.should eq Model::UserJWT::Permissions::Admin + end + + it "allows granted profile updates but requires Manage before changing foreign user privileges" do + f = build.call.not_nil! + grant = Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, + Model::Permissions::Read | Model::Permissions::Update).save! + path = "#{Users.base_route}#{f.acadian.user.id}?organisation_id=#{f.acadian.organisation.id}" + headers = Spec::Tenancy.headers(f.ucla.admin) + name = "Updated profile #{random_name}" + client.patch(path, headers: headers, body: {name: name}.to_json).status_code.should eq 200 + Model::User.find!(f.acadian.user.id.as(String)).name.should eq name + + original_digest = Model::User.find!(f.acadian.user.id.as(String)).password_digest + [{sys_admin: true}, {support: true}, {groups: ["customer-management"]}, {password: "Must need Manage 123!"}].each do |changes| + client.patch(path, headers: headers, body: changes.to_json).status_code.should eq 403 + user = Model::User.find!(f.acadian.user.id.as(String)) + user.sys_admin.should be_false + user.support.should be_false + user.groups.should be_empty + user.password_digest.should eq original_digest + end + + grant.permission_flags |= Model::Permissions::Manage + grant.save! + client.patch(path, headers: headers, body: {sys_admin: true, support: true, groups: ["customer-management"]}.to_json).status_code.should eq 200 + managed = Model::User.find!(f.acadian.user.id.as(String)) + managed.sys_admin.should be_true + managed.support.should be_true + managed.groups.should eq ["customer-management"] + end + + it "does not reveal customer OAuth and authentication secrets through a read grant" do + f = build.call.not_nil! + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, Model::Permissions::Read).save! + app = Model::Generator.doorkeeper_application(owner: f.acadian.authority).save! + oauth = Model::Generator.oauth_strat(f.acadian.authority).save! + ldap = Model::Generator.ldap_strat(f.acadian.authority) + ldap.password = "Directory credential #{random_name}" + ldap.save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + headers = Spec::Tenancy.headers(f.ucla.admin) + + apps = client.get("#{OAuthApplications.base_route}#{suffix}", headers: headers) + apps.status_code.should eq 200 + Spec::Tenancy.ids(apps.body).should contain(app.id.to_s) + apps.body.should_not contain(app.secret) + ["#{OAuthApplications.base_route}#{app.id}", "#{OAuthAuthentications.base_route}#{oauth.id}", + OAuthAuthentications.base_route, "#{LdapAuthentications.base_route}#{ldap.id}", LdapAuthentications.base_route].each do |path| + response = client.get("#{path}#{suffix}", headers: headers) + {200, 403}.includes?(response.status_code).should be_true + response.body.should_not contain(app.secret) + response.body.should_not contain(oauth.client_secret) + response.body.should_not contain(ldap.password.not_nil!) + end + end + + it "refuses tenant consent through a read grant before calling Microsoft Graph" do + f = build.call.not_nil! + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, Model::Permissions::Read).save! + WebMock.allow_net_connect = false + begin + response = client.get("#{TenantConsent.base_route}/#{f.acadian.authority.id}?organisation_id=#{f.acadian.organisation.id}", + headers: Spec::Tenancy.headers(f.ucla.admin)) + response.status_code.should eq 403 + ensure + WebMock.allow_net_connect = true + end + end + + it "requires Manage before restoring a deleted customer administrator through a creation grant" do + f = build.call.not_nil! + administrator = Model::Generator.user(f.acadian.authority, admin: true).save! + id = administrator.id.as(String) + administrator.destroy + Model::Generator.grant(f.ucla.admin, "organisation", f.acadian.organisation.id.to_s, + Model::Permissions::Read | Model::Permissions::Create).save! + + response = client.post("#{History.base_route}undelete?resource_type=user&resource_id=#{id}&organisation_id=#{f.acadian.organisation.id}", + headers: Spec::Tenancy.headers(f.ucla.admin)) + response.status_code.should eq 403 + Model::User.find?(id).should be_nil + end + + it "does not restore a selected system after its recorded module belongs to a sibling organisation" do + f = build.call.not_nil! + driver = Model::Generator.driver(role: Model::Driver::Role::Device).save! + mod = Model::Generator.module(driver).tap(&.organisation_id = f.acadian.organisation.id).save! + deleted = Model::Generator.control_system + deleted.organisation_id = f.acadian.organisation.id + deleted.zones = [f.acadian.building.id.as(String)] + deleted.modules = [mod.id.as(String)] + deleted.save! + id = deleted.id.as(String) + # Keep the device alive when the deleted system releases its modules. + f.ntt_staff.system.modules = f.ntt_staff.system.modules + [mod.id.as(String)] + f.ntt_staff.system.save! + deleted.destroy + mod.organisation_id = f.ntt_staff.organisation.id + mod.save! + + response = client.post("#{History.base_route}undelete?resource_type=sys&resource_id=#{id}&organisation_id=#{f.acadian.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin)) + response.status_code.should eq 404 + Model::ControlSystem.find?(id).should be_nil + end + it "checks changed API key users before saving" do f = build.call.not_nil! key = Model::ApiKey.new(name: "Stay here #{random_name}") diff --git a/spec/controllers/organisation_domain_scope_spec.cr b/spec/controllers/organisation_domain_scope_spec.cr index 96b8c1a9..39bc4dc4 100644 --- a/spec/controllers/organisation_domain_scope_spec.cr +++ b/spec/controllers/organisation_domain_scope_spec.cr @@ -19,6 +19,12 @@ module PlaceOS::Api global_storages.clear end if f = fixture + authorities = [f.ntt_staff.authority.id, f.acadian.authority.id, f.ucla.authority.id].compact + storage_ids = Model::Storage.where(authority_id: authorities).to_a.compact_map(&.id) + unless storage_ids.empty? + Model::Upload.where(storage_id: storage_ids).delete_all + Model::Storage.where(id: storage_ids).delete_all + end Spec::Tenancy.teardown(f) fixture = nil end @@ -77,6 +83,21 @@ module PlaceOS::Api Model::AssetType.find!(type.id.as(String)).category_id.should eq home.id end + it "rolls back a bulk asset create when a later asset refers to another organisation" do + f = build.call.not_nil! + own_category = Model::Generator.asset_category(f.ntt_staff.authority).save! + own_type = Model::Generator.asset_type(own_category).save! + foreign_category = Model::Generator.asset_category(f.acadian.authority).save! + foreign_type = Model::Generator.asset_type(foreign_category).save! + order = Model::Generator.asset_purchase_order(f.ntt_staff.authority).save! + first = Model::Asset.new(asset_type_id: own_type.id, purchase_order_id: order.id, zone_id: f.ntt_staff.building.id) + second = Model::Asset.new(asset_type_id: foreign_type.id, purchase_order_id: order.id, zone_id: f.acadian.building.id) + result = client.post("#{Assets.base_route}bulk?organisation_id=#{f.ntt_staff.organisation.id}", + headers: Spec::Tenancy.headers(f.ntt_staff.admin), body: [first, second].to_json) + result.status_code.should eq 404 + Model::Asset.where(asset_type_id: own_type.id).count.should eq 0 + end + it "lists groups in the selected domain and conceals sibling group ids" do f = build.call.not_nil! target = Model::Generator.group(authority: f.acadian.authority).save! @@ -89,6 +110,16 @@ module PlaceOS::Api domain_scope_get("#{Groups.base_route}#{home.id}#{suffix}", f.ntt_staff.admin).status_code.should eq 404 end + it "preserves a name-only group PATCH without an authority field" do + f = build.call.not_nil! + group = Model::Generator.group(authority: f.acadian.authority).save! + result = client.patch("#{Groups.base_route}#{group.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "Renamed without authority"}.to_json) + result.status_code.should eq 200 + updated = Model::Group.find!(group.id.as(UUID)) + updated.name.should eq "Renamed without authority" + updated.authority_id.should eq f.acadian.authority.id + end + it "reads the selected customer's signage playlist" do f = build.call.not_nil! target = Model::Generator.playlist(authority: f.acadian.authority).save! @@ -180,6 +211,42 @@ module PlaceOS::Api JSON.parse(second.body)["upload_id"].as_s.should_not eq first_id end + it "does not let a read-only upload OAuth scope sign a new upload" do + f = build.call.not_nil! + headers = Spec::Tenancy.headers(f.acadian.admin) + token = Model::UserJWT.decode(headers["Authorization"].split(' ').last) + scopes = [Model::UserJWT::Scope.new("uploads", Model::UserJWT::Scope::Access::Read)] + headers["Authorization"] = "Bearer #{Model::UserJWT.new(iss: token.iss, iat: token.iat, exp: token.exp, domain: token.domain, id: token.id, user: token.user, scope: scopes).encode}" + result = client.post(Uploads.base_route, headers: headers, + body: {file_name: "read-only.png", file_size: 50, file_id: "checksum", file_mime: "image/png"}.to_json) + result.status_code.should eq 403 + end + + it "does not send a brand-logo upload from another organisation to the image vendor" do + f = build.call.not_nil! + storage = Model::Generator.storage(authority_id: f.acadian.authority.id).save! + foreign_storage = Model::Generator.storage(authority_id: f.ucla.authority.id).save! + Model::Generator.signage_ai_provider(authority: f.acadian.authority, name: "selected-#{random_name}", is_default: true).save! + source = Model::Generator.upload(f.ntt_staff.admin, storage.id, file_name: "source.png").save! + logo = Model::Generator.upload(f.ucla.admin, foreign_storage.id, file_name: "foreign-logo.png").save! + Model::Metadata.new(parent_id: f.acadian.org_zone.id, name: "signage_ai", details: JSON.parse({logo_upload_id: logo.id}.to_json)).save! + HttpMocks.signage_ai_vendor + HttpMocks.signage_ai_storage + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + result = client.post("#{SignageAI.base_route}/edit?organisation_id=#{f.acadian.organisation.id}", headers: headers, + body: {prompt: "make it warmer", candidates: 1, include_logo: true, source_upload_id: source.id}.to_json) + result.status_code.should eq 202 + job_id = UUID.new(JSON.parse(result.body)["id"].as_s) + job = Model::SignageAIJob.find!(job_id) + 100.times do + break if job.final? + sleep 100.milliseconds + job = Model::SignageAIJob.find!(job_id) + end + job.final?.should be_true + job.upload_ids.should_not contain(logo.id) + end + it "requires an explicit domain when a selected foreign organisation has several authorities" do f = build.call.not_nil! extra = Model::Generator.authority("second.acadian.test").tap(&.organisation_id = f.acadian.organisation.id).save! diff --git a/spec/controllers/organisation_mqtt_scope_spec.cr b/spec/controllers/organisation_mqtt_scope_spec.cr new file mode 100644 index 00000000..dc6bdc76 --- /dev/null +++ b/spec/controllers/organisation_mqtt_scope_spec.cr @@ -0,0 +1,112 @@ +require "../helper" + +module PlaceOS::Api + private def self.organisation_mqtt_access(topic : String, user : Model::User, access : Int32 = 4) + headers = Spec::Tenancy.headers(user) + # Mosquitto calls REST on its service hostname, not the token's domain. + headers["Host"] = "broker.internal" + query = URI::Params.encode({"topic" => topic, "acc" => access.to_s}) + client.post("#{MQTT.base_route}access?#{query}", headers: headers) + end + + describe "organisation MQTT isolation" do + fixture = nil.as(Spec::Tenancy::Fixture?) + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if cleanup = fixture + Spec::Tenancy.teardown(cleanup) + fixture = nil + end + end + + it "allows a concrete owned authority topic and denies foreign or unbounded subscriptions" do + f = fixture = Spec::Tenancy.build + organisation_mqtt_access("placeos/#{f.acadian.authority.id}/metadata/changed", f.acadian.user).status_code.should eq 200 + organisation_mqtt_access("placeos/#{f.ucla.authority.id}/metadata/changed", f.acadian.user).status_code.should eq 403 + {"#", "placeos/+/#", "placeos/internal/chat/#", "placeos/org/metadata/#"}.each do |topic| + organisation_mqtt_access(topic, f.acadian.user).status_code.should eq 403 + end + end + + it "scopes source metadata by the concrete model rather than the common org topic label" do + f = fixture = Spec::Tenancy.build + organisation_mqtt_access("placeos/org/metadata/#{f.acadian.org_zone.id}", f.acadian.user).status_code.should eq 200 + organisation_mqtt_access("placeos/org/metadata/#{f.ucla.org_zone.id}", f.acadian.user).status_code.should eq 403 + end + + it "checks both the source state scope zone and its concrete system" do + f = fixture = Spec::Tenancy.build + own = "placeos/#{f.acadian.org_zone.id}/state/_/#{f.acadian.building.id}/_/_/#{f.acadian.system.id}/#{f.acadian.mod.driver_id}/#{f.acadian.mod.resolved_name}/1/power" + foreign = "placeos/#{f.ucla.org_zone.id}/state/_/#{f.ucla.building.id}/_/_/#{f.ucla.system.id}/#{f.ucla.mod.driver_id}/#{f.ucla.mod.resolved_name}/1/power" + organisation_mqtt_access(own, f.acadian.user).status_code.should eq 200 + organisation_mqtt_access(foreign, f.acadian.user).status_code.should eq 403 + spoofed = own.sub(f.acadian.system.id.as(String), f.ucla.system.id.as(String)) + organisation_mqtt_access(spoofed, f.acadian.user).status_code.should eq 403 + end + + it "keeps an authority read grant exact and unable to publish" do + f = fixture = Spec::Tenancy.build + secondary = Model::Generator.authority("secondary.test") + secondary.organisation_id = f.acadian.organisation.id + secondary.save! + Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "authority", scope_id: f.acadian.authority.id.as(String), permissions: Model::Permissions::Read.to_i).save! + own_domain = "placeos/#{f.acadian.authority.id}/event/changed" + organisation_mqtt_access(own_domain, f.ucla.admin).status_code.should eq 200 + organisation_mqtt_access("placeos/#{secondary.id}/event/changed", f.ucla.admin).status_code.should eq 403 + organisation_mqtt_access(own_domain, f.ucla.admin, 2).status_code.should eq 403 + organisation_mqtt_access("placeos/org/metadata/#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 403 + end + + it "refreshes support privileges before allowing MQTT writes" do + f = fixture = Spec::Tenancy.build + headers = Spec::Tenancy.headers(f.acadian.support) + f.acadian.support.support = false + f.acadian.support.save! + query = URI::Params.encode({"topic" => "placeos/#{f.acadian.authority.id}/control", "acc" => "2"}) + client.post("#{MQTT.base_route}access?#{query}", headers: headers).status_code.should eq 403 + end + + it "rejects expired JWTs even on established-connection ACL checks" do + f = fixture = Spec::Tenancy.build + headers = Spec::Tenancy.headers(f.acadian.user) + original = Model::UserJWT.decode(headers["Authorization"].split(' ').last) + expired = Model::UserJWT.new(iss: original.iss, iat: original.iat, exp: 1.second.ago, domain: original.domain, id: original.id, user: original.user, scope: original.scope) + headers["Authorization"] = "Bearer #{expired.encode}" + query = URI::Params.encode({"topic" => "placeos/#{f.acadian.authority.id}/event", "acc" => "4"}) + client.post("#{MQTT.base_route}access?#{query}", headers: headers).status_code.should eq 401 + end + + it "rejects an expired API key and an API key whose owner was deleted" do + f = fixture = Spec::Tenancy.build + key = Model::ApiKey.new(name: "MQTT #{random_name}") + key.user = f.acadian.user + credential = key.x_api_key.not_nil! + key.save! + headers = HTTP::Headers{"Authorization" => credential, "Host" => "broker.internal"} + client.post("#{MQTT.base_route}user", headers: headers).status_code.should eq 200 + PgORM::Database.connection do |db| + db.exec("UPDATE api_key SET expires_at = $1 WHERE id = $2", args: [1.second.ago, key.id.as(String)]) + end + client.post("#{MQTT.base_route}user", headers: headers).status_code.should eq 401 + PgORM::Database.connection do |db| + db.exec("UPDATE api_key SET expires_at = NULL WHERE id = $1", args: [key.id.as(String)]) + end + f.acadian.user.deleted = true + f.acadian.user.save! + client.post("#{MQTT.base_route}user", headers: headers).status_code.should eq 401 + end + + it "preserves wildcard broker access for explicit management staff" do + f = fixture = Spec::Tenancy.build + organisation_mqtt_access("#", f.placeos.admin).status_code.should eq 200 + organisation_mqtt_access("placeos/#", f.placeos.admin, 2).status_code.should eq 200 + end + + it "retains the legacy ACL when enforcement is disabled" do + f = fixture = Spec::Tenancy.build + Utils::Tenancy.enforce = false + organisation_mqtt_access("#", f.acadian.user).status_code.should eq 200 + end + end +end diff --git a/spec/controllers/organisation_multi_domain_scope_spec.cr b/spec/controllers/organisation_multi_domain_scope_spec.cr new file mode 100644 index 00000000..bc22de9b --- /dev/null +++ b/spec/controllers/organisation_multi_domain_scope_spec.cr @@ -0,0 +1,207 @@ +require "../helper" + +module PlaceOS::Api + describe "organisation collections spanning domains" do + fixture = nil.as(Spec::Tenancy::Fixture?) + second = nil.as(Model::Authority?) + global_storages = [] of String + build = -> { + fixture = f = Spec::Tenancy.build + second = Model::Generator.authority("second.acadian.test").tap(&.organisation_id = f.acadian.organisation.id).save! + {f, second.not_nil!} + } + + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if f = fixture + authorities = [f.ntt_staff.authority.id, f.acadian.authority.id, f.ucla.authority.id, second.try(&.id)].compact + storage_ids = Model::Storage.where(authority_id: authorities).to_a.compact_map(&.id) + global_storages + unless storage_ids.empty? + Model::Upload.where(storage_id: storage_ids).delete_all + Model::Storage.where(id: storage_ids).delete_all + end + global_storages.clear + Spec::Tenancy.teardown(f) + fixture = nil + second = nil + end + end + + it "lists both domains' asset collections before applying pagination" do + f, other = build.call + first_category = Model::Generator.asset_category(f.acadian.authority).save! + second_category = Model::Generator.asset_category(other).save! + first_type = Model::Generator.asset_type(first_category).save! + second_type = Model::Generator.asset_type(second_category).save! + first_order = Model::Generator.asset_purchase_order(f.acadian.authority).save! + second_order = Model::Generator.asset_purchase_order(other).save! + first_asset = Model::Asset.new(asset_type_id: first_type.id, purchase_order_id: first_order.id, zone_id: f.acadian.building.id).save! + second_asset = Model::Asset.new(asset_type_id: second_type.id, purchase_order_id: second_order.id, zone_id: f.acadian.building.id).save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + suffix = "?organisation_id=#{f.acadian.organisation.id}" + [ + {AssetCategories.base_route, first_category.id, second_category.id}, + {AssetTypes.base_route, first_type.id, second_type.id}, + {AssetPurchaseOrders.base_route, first_order.id, second_order.id}, + {Assets.base_route, first_asset.id, second_asset.id}, + ].each do |(path, first_id, second_id)| + response = client.get("#{path}#{suffix}", headers: headers) + response.status_code.should eq 200 + Spec::Tenancy.ids(response.body).sort.should eq [first_id.as(String), second_id.as(String)].sort + end + page = client.get("#{AssetCategories.base_route}#{suffix}&limit=1", headers: headers) + page.status_code.should eq 200 + page.headers["X-Total-Count"].should eq "2" + Spec::Tenancy.ids(page.body).size.should eq 1 + end + + it "keeps implicit home-domain results and only broadens after explicit organisation selection" do + f, other = build.call + first = Model::Generator.asset_category(f.acadian.authority).save! + second_category = Model::Generator.asset_category(other).save! + headers = Spec::Tenancy.headers(f.acadian.admin) + home = client.get(AssetCategories.base_route, headers: headers) + home.status_code.should eq 200 + Spec::Tenancy.ids(home.body).should eq [first.id] + selected = client.get("#{AssetCategories.base_route}?organisation_id=#{f.acadian.organisation.id}", headers: headers) + selected.status_code.should eq 200 + Spec::Tenancy.ids(selected.body).sort.should eq [first.id.as(String), second_category.id.as(String)].sort + end + + it "narrows an organisation collection by an explicit authority and exact authority grant" do + f, other = build.call + first = Model::Generator.asset_category(f.acadian.authority).save! + second_category = Model::Generator.asset_category(other).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}" + result = client.get("#{AssetCategories.base_route}#{suffix}&authority_id=#{other.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should eq [second_category.id] + client.get("#{AssetCategories.base_route}#{suffix}&authority_id=#{f.ntt_staff.authority.id}", headers: Spec::Tenancy.headers(f.ntt_staff.admin)).status_code.should eq 404 + Model::Generator.grant(f.ucla.admin, "authority", other.id.as(String), Model::Permissions::Read).save! + granted = client.get("#{AssetCategories.base_route}#{suffix}", headers: Spec::Tenancy.headers(f.ucla.admin)) + granted.status_code.should eq 200 + Spec::Tenancy.ids(granted.body).should eq [second_category.id] + Spec::Tenancy.ids(granted.body).should_not contain(first.id) + end + + it "lists groups and signage from every selected domain with scoped counts" do + f, other = build.call + first_group = Model::Generator.group(authority: f.acadian.authority).save! + second_group = Model::Generator.group(authority: other).save! + first_playlist = Model::Generator.playlist(authority: f.acadian.authority).save! + second_playlist = Model::Generator.playlist(authority: other).save! + first_item = Model::Generator.item(authority: f.acadian.authority).save! + second_item = Model::Generator.item(authority: other).save! + first_template = Model::Generator.signage_template(authority: f.acadian.authority).save! + second_template = Model::Generator.signage_template(authority: other).save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + suffix = "?organisation_id=#{f.acadian.organisation.id}" + [ + {Groups.base_route, first_group.id.to_s, second_group.id.to_s}, + {Playlist.base_route, first_playlist.id.as(String), second_playlist.id.as(String)}, + {PlaylistMedia.base_route, first_item.id.as(String), second_item.id.as(String)}, + {SignageTemplates.base_route, first_template.id.to_s, second_template.id.to_s}, + ].each do |(path, first_id, second_id)| + result = client.get("#{path}#{suffix}", headers: headers) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).sort.should eq [first_id, second_id].sort + result.headers["X-Total-Count"].should eq "2" + end + end + + it "aggregates media tags across selected domains without sibling organisation tags" do + f, other = build.call + Model::Generator.item(authority: f.acadian.authority).tap(&.tags = Set{"common", "first-domain"}).save! + Model::Generator.item(authority: other).tap(&.tags = Set{"common", "second-domain"}).save! + Model::Generator.item(authority: f.ucla.authority).tap(&.tags = Set{"foreign"}).save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + suffix = "?organisation_id=#{f.acadian.organisation.id}" + tags = client.get("#{PlaylistMedia.base_route}/tags#{suffix}", headers: headers) + tags.status_code.should eq 200 + Array(String).from_json(tags.body).sort.should eq ["common", "first-domain", "second-domain"].sort + counts = client.get("#{PlaylistMedia.base_route}/tag_counts#{suffix}", headers: headers) + counts.status_code.should eq 200 + JSON.parse(counts.body)["common"].as_i.should eq 2 + JSON.parse(counts.body)["foreign"]?.should be_nil + end + + it "lists uploads and counts across authority-specific default storage" do + f, other = build.call + first_storage = Model::Generator.storage(authority_id: f.acadian.authority.id).save! + second_storage = Model::Generator.storage(authority_id: other.id).save! + first = Model::Generator.upload(f.acadian.admin, first_storage.id).save! + second_upload = Model::Generator.upload(f.acadian.admin, second_storage.id).save! + suffix = "?organisation_id=#{f.acadian.organisation.id}&limit=1" + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + first_page = client.get("#{Uploads.base_route}#{suffix}", headers: headers) + first_page.status_code.should eq 200 + first_page.headers["X-Total-Count"].should eq "2" + second_page = client.get("#{Uploads.base_route}#{suffix}&offset=1", headers: headers) + second_page.status_code.should eq 200 + (Spec::Tenancy.ids(first_page.body) + Spec::Tenancy.ids(second_page.body)).sort.should eq [first.id.as(String), second_upload.id.as(String)].sort + end + + it "scopes shared-storage uploads by their recorded target authority across selected domains" do + f, other = build.call + storage = Model::Generator.storage.save! + global_storages << storage.id.as(String) + first = Model::Generator.upload(f.acadian.admin, storage.id).tap { |row| row.object_options["authority_id"] = JSON::Any.new(f.acadian.authority.id.as(String)) }.save! + second_upload = Model::Generator.upload(f.acadian.admin, storage.id).tap { |row| row.object_options["authority_id"] = JSON::Any.new(other.id.as(String)) }.save! + foreign = Model::Generator.upload(f.ucla.admin, storage.id).tap { |row| row.object_options["authority_id"] = JSON::Any.new(f.ucla.authority.id.as(String)) }.save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + result = client.get("#{Uploads.base_route}?organisation_id=#{f.acadian.organisation.id}&storage_id=#{storage.id}", headers: headers) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).sort.should eq [first.id.as(String), second_upload.id.as(String)].sort + Spec::Tenancy.ids(result.body).should_not contain(foreign.id) + own = client.get("#{Uploads.base_route}?storage_id=#{storage.id}", headers: Spec::Tenancy.headers(f.acadian.admin)) + own.status_code.should eq 200 + Spec::Tenancy.ids(own.body).should eq [first.id] + end + + it "lists alert, storage, provider and mail collections from every selected domain" do + f, other = build.call + first_dashboard = Model::Generator.alert_dashboard(authority_id: f.acadian.authority.id).save! + second_dashboard = Model::Generator.alert_dashboard(authority_id: other.id).save! + first_alert = Model::Generator.alert(alert_dashboard_id: first_dashboard.id).save! + second_alert = Model::Generator.alert(alert_dashboard_id: second_dashboard.id).save! + first_storage = Model::Generator.storage(authority_id: f.acadian.authority.id).save! + second_storage = Model::Generator.storage(authority_id: other.id).save! + first_provider = Model::Generator.signage_ai_provider(authority: f.acadian.authority, name: "first-#{random_name}").save! + second_provider = Model::Generator.signage_ai_provider(authority: other, name: "second-#{random_name}").save! + first_mail = Model::Generator.pending_mail(authority: f.acadian.authority, user: f.acadian.admin).save! + second_mail = Model::Generator.pending_mail(authority: other, user: f.acadian.admin).save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + suffix = "?organisation_id=#{f.acadian.organisation.id}" + [ + {AlertDashboards.base_route, first_dashboard.id.to_s, second_dashboard.id.to_s}, + {Alerts.base_route, first_alert.id.to_s, second_alert.id.to_s}, + {Storages.base_route, first_storage.id.to_s, second_storage.id.to_s}, + {SignageAIProviders.base_route, first_provider.id.to_s, second_provider.id.to_s}, + {PendingMails.base_route, first_mail.id.to_s, second_mail.id.to_s}, + ].each do |(path, first_id, second_id)| + result = client.get("#{path}#{suffix}", headers: headers) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should contain(first_id) + Spec::Tenancy.ids(result.body).should contain(second_id) + end + end + + it "lists AI jobs across selected domains and infers each direct job's authority" do + f, other = build.call + first = Model::Generator.signage_ai_job(authority: f.acadian.authority, user: f.ntt_staff.admin, state: Model::SignageAIJob::State::Done).save! + second_job = Model::Generator.signage_ai_job(authority: other, user: f.ntt_staff.admin, state: Model::SignageAIJob::State::Done).save! + map_job = Model::Generator.signage_ai_job(authority: other, user: f.ntt_staff.admin, kind: Model::SignageAIJob::Kind::MapEdit, state: Model::SignageAIJob::State::Done).save! + headers = Spec::Tenancy.headers(f.ntt_staff.admin) + suffix = "?organisation_id=#{f.acadian.organisation.id}" + jobs = client.get("#{SignageAI.base_route}/jobs#{suffix}", headers: headers) + jobs.status_code.should eq 200 + Spec::Tenancy.ids(jobs.body).sort.should eq [first.id.to_s, second_job.id.to_s].sort + client.get("#{SignageAI.base_route}/jobs/#{second_job.id}#{suffix}", headers: headers).status_code.should eq 200 + maps = client.get("#{MapAI.base_route}/jobs#{suffix}", headers: headers) + maps.status_code.should eq 200 + Spec::Tenancy.ids(maps.body).should eq [map_job.id.to_s] + client.get("#{MapAI.base_route}/jobs/#{map_job.id}#{suffix}", headers: headers).status_code.should eq 200 + end + end +end diff --git a/spec/controllers/organisation_selection_spec.cr b/spec/controllers/organisation_selection_spec.cr index 0d826a12..6ad8341a 100644 --- a/spec/controllers/organisation_selection_spec.cr +++ b/spec/controllers/organisation_selection_spec.cr @@ -122,7 +122,7 @@ module PlaceOS::Api result = selection_get("#{Organisations.base_route}?limit=500", f.ucla.user) result.status_code.should eq 200 organisations = JSON.parse(result.body).as_a - organisations.map(&.["id"].as_s).sort.should eq [f.ucla.organisation.id.to_s, f.acadian.organisation.id.to_s].sort + organisations.map(&.["id"].as_s).sort!.should eq [f.ucla.organisation.id.to_s, f.acadian.organisation.id.to_s].sort organisations.each do |organisation| organisation["config"]?.should be_nil organisation["payer"]?.should be_nil @@ -187,6 +187,54 @@ module PlaceOS::Api selection_get(path, f.ucla.admin).status_code.should eq 404 end + it "keeps public guest token issuance domain-bound and unauthenticated under enforcement" do + f = build.call.not_nil! + f.acadian.system.public = true + f.acadian.system.save! + f.acadian.authority.internals_will_change! + f.acadian.authority.internals["recaptcha_skip"] = JSON::Any.new(true) + f.acadian.authority.save! + result = client.post("#{PublicEvents.base_route}guest_token/#{f.acadian.system.id}", + headers: HTTP::Headers{"Host" => f.acadian.authority.domain, "Content-Type" => "application/json"}, + body: {captcha: "skip", name: "Guest", email: "guest@external.test"}.to_json) + + # An absent JWT_SECRET disables issuance, but organisation enforcement + # must not turn this public route into an authenticated resource route. + result.status_code.should eq(PublicEvents::JWT_SECRET ? 200 : 503) + end + + it "preserves invited guests' home-domain public events without allowing foreign organisation selection" do + f = build.call.not_nil! + f.acadian.system.public = true + f.acadian.system.save! + token = Model::UserJWT.new( + iss: Model::UserJWT::ISSUER, + iat: 5.minutes.ago, + exp: 1.hour.from_now, + domain: f.acadian.authority.domain, + id: f.acadian.user.id.as(String), + user: Model::UserJWT::Metadata.new(name: "Invited guest", email: "guest@external.test", + permissions: Model::UserJWT::Permissions::User, roles: [f.acadian.system.id.as(String)]), + scope: [Model::UserJWT::Scope::GUEST], + ) + headers = HTTP::Headers{"Host" => f.acadian.authority.domain, "Content-Type" => "application/json", "Authorization" => "Bearer #{token.encode}"} + path = "#{PublicEvents.base_route}#{f.acadian.system.id}/events" + result = client.get(path, headers: headers) + result.status_code.should eq 200 + JSON.parse(result.body).as_a.should be_empty + client.get("#{path}?organisation_id=#{f.ucla.organisation.id}", headers: headers).status_code.should eq 404 + end + + it "keeps discovery restricted to real reach even when resource enforcement is disabled" do + f = build.call.not_nil! + Utils::Tenancy.enforce = false + result = selection_get("#{Organisations.base_route}?limit=500", f.acadian.user) + result.status_code.should eq 200 + Spec::Tenancy.ids(result.body).should eq [f.acadian.organisation.id.to_s] + selection_get("#{Organisations.base_route}#{f.acadian.organisation.id}", f.acadian.user).status_code.should eq 200 + selection_get("#{Organisations.base_route}#{f.ucla.organisation.id}", f.acadian.user).status_code.should eq 404 + end + it "retains legacy request behaviour when enforcement is disabled" do f = build.call.not_nil! Utils::Tenancy.enforce = false diff --git a/spec/controllers/tenancy_spec.cr b/spec/controllers/tenancy_spec.cr index b437307f..867bebb9 100644 --- a/spec/controllers/tenancy_spec.cr +++ b/spec/controllers/tenancy_spec.cr @@ -1,10 +1,12 @@ require "../helper" -private def tenancy_get(path, user) +private def tenancy_get(path, user, organisation_id : UUID? = nil) + path = "#{path}#{path.includes?('?') ? '&' : '?'}organisation_id=#{organisation_id}" if organisation_id client.get(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user)) end -private def tenancy_post(path, user, body) +private def tenancy_post(path, user, body, organisation_id : UUID? = nil) + path = "#{path}#{path.includes?('?') ? '&' : '?'}organisation_id=#{organisation_id}" if organisation_id client.post(path, headers: PlaceOS::Api::Spec::Tenancy.headers(user), body: body.to_json) end @@ -54,14 +56,14 @@ module PlaceOS::Api zones.should_not contain(f.ucla.org_zone.id) zones.should_not contain(f.unowned_zone.id) - partner_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.ntt_staff.support).body) + partner_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.ntt_staff.support, f.acadian.organisation.id).body) partner_zones.should contain(f.acadian.org_zone.id) - partner_zones.should contain(f.ntt_staff.org_zone.id) + partner_zones.should_not contain(f.ntt_staff.org_zone.id) partner_zones.should_not contain(f.ucla.org_zone.id) - cluster_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.placeos.admin).body) + cluster_zones = Spec::Tenancy.ids(tenancy_get("#{Zones.base_route}?limit=500", f.placeos.admin, f.ucla.organisation.id).body) cluster_zones.should contain(f.ucla.org_zone.id) - cluster_zones.should contain(f.unowned_zone.id) + cluster_zones.should_not contain(f.unowned_zone.id) systems = Spec::Tenancy.ids(tenancy_get("#{Systems.base_route}?limit=500", f.ucla.admin).body) systems.should eq [f.ucla.system.id] @@ -82,12 +84,12 @@ module PlaceOS::Api tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.acadian.admin).status_code.should eq 404 # partner staff reach their client, not a stranger - tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ntt_staff.admin).status_code.should eq 200 - tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.ntt_staff.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ntt_staff.admin, f.acadian.organisation.id).status_code.should eq 200 + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.ntt_staff.admin, f.acadian.organisation.id).status_code.should eq 404 - # cluster admins reach everything, unowned rows included - tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.placeos.admin).status_code.should eq 200 - tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.placeos.admin).status_code.should eq 200 + # Management staff select the target organisation; unowned estate is reserved for explicit claiming. + tenancy_get("#{Zones.base_route}#{f.ucla.org_zone.id}", f.placeos.admin, f.ucla.organisation.id).status_code.should eq 200 + tenancy_get("#{Zones.base_route}#{f.unowned_zone.id}", f.placeos.admin, f.ucla.organisation.id).status_code.should eq 404 end it "narrows a list to one organisation on request" do @@ -134,7 +136,7 @@ module PlaceOS::Api named.status_code.should eq 201 JSON.parse(named.body)["organisation_id"].to_s.should eq f.ucla.organisation.id.to_s - client.post("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "Not mine #{random_name}"}.to_json).status_code.should eq 403 + client.post("#{Zones.base_route}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "Not mine #{random_name}"}.to_json).status_code.should eq 404 end it "owns new systems through their zones and refuses mixed zones" do @@ -146,8 +148,8 @@ module PlaceOS::Api tenancy_post(Systems.base_route, f.acadian.admin, {name: "Room #{random_name}", zones: [f.ucla.building.id]}).status_code.should eq 404 - mixed = tenancy_post(Systems.base_route, f.placeos.admin, {name: "Room #{random_name}", zones: [f.acadian.building.id, f.ucla.building.id]}) - mixed.status_code.should eq 422 + mixed = tenancy_post(Systems.base_route, f.placeos.admin, {name: "Room #{random_name}", zones: [f.acadian.building.id, f.ucla.building.id]}, f.acadian.organisation.id) + mixed.status_code.should eq 404 end it "keeps modules inside the system's organisation" do @@ -178,7 +180,7 @@ module PlaceOS::Api JSON.parse(staff.body)["organisation_id"].to_s.should eq f.ucla.organisation.id.to_s moved = client.patch("#{Domains.base_route}#{f.acadian.authority.id}?organisation_id=#{f.ucla.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "renamed"}.to_json) - moved.status_code.should eq 403 + moved.status_code.should eq 404 end it "lists users within reach only" do @@ -191,7 +193,7 @@ module PlaceOS::Api tenancy_get("#{Users.base_route}?authority_id=#{f.ucla.authority.id}", f.acadian.admin).status_code.should eq 404 tenancy_get("#{Users.base_route}#{f.ucla.user.id}", f.acadian.admin).status_code.should eq 404 - partner_users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?limit=500", f.ntt_staff.admin).body) + partner_users = Spec::Tenancy.ids(tenancy_get("#{Users.base_route}?limit=500", f.ntt_staff.admin, f.acadian.organisation.id).body) partner_users.should contain(f.acadian.user.id) partner_users.should_not contain(f.ucla.user.id) end @@ -206,7 +208,7 @@ module PlaceOS::Api second = Model::Generator.user(f.acadian.authority, admin: true).save! client.delete("#{Users.base_route}#{second.id}", headers: Spec::Tenancy.headers(f.acadian.admin)).status_code.should eq 202 - client.delete("#{Users.base_route}#{f.acadian.admin.id}", headers: Spec::Tenancy.headers(f.placeos.admin)).status_code.should eq 202 + client.delete("#{Users.base_route}#{f.acadian.admin.id}?organisation_id=#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.placeos.admin)).status_code.should eq 202 end end @@ -219,7 +221,7 @@ module PlaceOS::Api template = tenancy_post(Triggers.base_route, f.acadian.admin, {name: "Template #{random_name}"}) template.status_code.should eq 403 - template = tenancy_post(Triggers.base_route, f.placeos.admin, {name: "Template #{random_name}"}) + template = tenancy_post(Triggers.base_route, f.placeos.admin, {name: "Template #{random_name}"}, f.placeos.organisation.id) template.status_code.should eq 201 # templates are readable by every organisation @@ -234,12 +236,12 @@ module PlaceOS::Api end describe "routes added since the reach enforcement" do - it "keeps change history and the source resync to cluster admins" do + it "scopes change history to the organisation while keeping source resync cluster-only" do f = build.call.not_nil! - tenancy_get(History.base_route, f.acadian.admin).status_code.should eq 403 - tenancy_get(History.base_route, f.placeos.admin).status_code.should eq 200 - tenancy_post(File.join(History.base_route, "undelete?resource_type=zone&resource_id=#{f.ucla.org_zone.id}"), f.acadian.admin, nil).status_code.should eq 403 + tenancy_get(History.base_route, f.acadian.admin).status_code.should eq 200 + tenancy_get(History.base_route, f.placeos.admin, f.acadian.organisation.id).status_code.should eq 200 + tenancy_post(File.join(History.base_route, "undelete?resource_type=zone&resource_id=#{f.ucla.org_zone.id}"), f.acadian.admin, nil).status_code.should eq 404 tenancy_post("/api/engine/v2/source/resync", f.acadian.admin, nil).status_code.should eq 403 tenancy_get("/api/engine/v2/source/resync", f.acadian.admin).status_code.should eq 403 @@ -274,21 +276,22 @@ module PlaceOS::Api client.patch("#{Organisations.base_route}#{f.acadian.organisation.id}", headers: Spec::Tenancy.headers(f.acadian.admin), body: {name: "renamed"}.to_json).status_code.should eq 403 end - it "widens reach through live grants" do + it "allows explicit selection through live grants without changing the home default" do f = build.call.not_nil! tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 granted = tenancy_post(Grants.base_route, f.placeos.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: 1}) granted.status_code.should eq 201 - tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 200 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin, f.acadian.organisation.id).status_code.should eq 200 client.delete("#{Grants.base_route}#{JSON.parse(granted.body)["id"]}", headers: Spec::Tenancy.headers(f.placeos.admin)).status_code.should eq 202 - tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin, f.acadian.organisation.id).status_code.should eq 404 expired = tenancy_post(Grants.base_route, f.placeos.admin, {user_id: f.ucla.admin.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: 1, expires_at: 1.hour.ago}) expired.status_code.should eq 201 - tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin).status_code.should eq 404 + tenancy_get("#{Zones.base_route}#{f.acadian.org_zone.id}", f.ucla.admin, f.acadian.organisation.id).status_code.should eq 404 # an organisation admin may grant into their own organisation but not a stranger's tenancy_post(Grants.base_route, f.acadian.admin, {user_id: f.ucla.support.id, scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s}).status_code.should eq 201 diff --git a/spec/mcp_resources_spec.cr b/spec/mcp_resources_spec.cr index 1a5c816e..38d3c527 100644 --- a/spec/mcp_resources_spec.cr +++ b/spec/mcp_resources_spec.cr @@ -87,10 +87,10 @@ module PlaceOS::Api client = MCPResourcesClient.new(Spec::Authentication.headers) result = client.request("resources/templates/list")["result"] templates = result["resourceTemplates"].as_a.map(&.["uriTemplate"].as_s) - templates.should contain "placeos://modules/{id}/state" - templates.should contain "placeos://modules/{id}/state/{key}" - templates.should contain "placeos://systems/{sys_id}/{module_slug}/{key}" - templates.should contain "placeos://modules/{id}/logs{?seconds,level}" + templates.should contain "placeos://modules/{id}/state{?organisation_id}" + templates.should contain "placeos://modules/{id}/state/{key}{?organisation_id}" + templates.should contain "placeos://systems/{sys_id}/{module_slug}/{key}{?organisation_id}" + templates.should contain "placeos://modules/{id}/logs{?seconds,level,organisation_id}" discovered = client.request("server/discover")["result"] discovered["capabilities"]["resources"]["subscribe"].should be_true diff --git a/spec/module_logs_spec.cr b/spec/module_logs_spec.cr index 2a25f788..247443d7 100644 --- a/spec/module_logs_spec.cr +++ b/spec/module_logs_spec.cr @@ -60,6 +60,52 @@ module PlaceOS::Api Time.measure { capture.wait(5.seconds, context) }.should be < 2.seconds end + it "stops writing and finishes when an organisation grant is revoked" do + fixture = nil.as(Spec::Tenancy::Fixture?) + f = fixture = Spec::Tenancy.build + token = Model::UserJWT.decode(Spec::Tenancy.headers(f.ucla.admin)["Authorization"].split(' ').last) + policy = Utils::Tenancy::Policy.new(token, f.ucla.authority.id.as(String), f.acadian.organisation.id) + permissions = Model::Permissions::Read | Model::Permissions::Operate + grant = Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: permissions.to_i).save! + output = IO::Memory.new + capture = Utils::ModuleLogCapture.new(output, authorize: -> { policy.module_debug_access?(f.acadian.mod.id.as(String)) }) + capture.write(::Log::Severity::Info, "authorised before revocation") + output.to_s.should contain "authorised before revocation" + grant.destroy + capture.write(::Log::Severity::Info, "private after revocation") + output.to_s.should_not contain "private after revocation" + capture.finished?.should be_true + Time.measure { capture.wait(5.seconds) }.should be < 1.second + ensure + if cleanup = fixture + Spec::Tenancy.teardown(cleanup) + end + end + + it "fails closed when a live permission check cannot be completed" do + output = IO::Memory.new + unavailable = true + capture = Utils::ModuleLogCapture.new(output, authorize: -> { + raise "permission lookup unavailable" if unavailable + true + }) + capture.write(::Log::Severity::Info, "private") + output.to_s.should be_empty + capture.finished?.should be_true + end + + it "ends a quiet capture when access is revoked without waiting for another log line" do + allowed = true + capture = Utils::ModuleLogCapture.new(IO::Memory.new, authorize: -> { allowed }) + spawn do + sleep 100.milliseconds + allowed = false + end + elapsed = Time.measure { capture.wait(5.seconds) } + elapsed.should be < 2.seconds + capture.finished?.should be_true + end + it "ends when stopped, i.e. core closed the debug socket" do capture = Utils::ModuleLogCapture.new(IO::Memory.new) spawn do diff --git a/spec/webrtc/organisation_scope_spec.cr b/spec/webrtc/organisation_scope_spec.cr new file mode 100644 index 00000000..1b357e44 --- /dev/null +++ b/spec/webrtc/organisation_scope_spec.cr @@ -0,0 +1,101 @@ +require "../helper" + +module PlaceOS::Api + private def self.domain_signaller(user : Model::User, &) + headers = Spec::Tenancy.headers(user) + token = headers["Authorization"].split(' ').last + socket = client.establish_ws("#{WebRTC.base_route}signaller?bearer_token=#{token}", headers: HTTP::Headers{"Host" => headers["Host"]}) + signals = Channel(SessionSignal).new(32) + socket.on_message do |message| + signal = SessionSignal.from_json(message) + signals.send(signal) unless signal.type.ping? + end + spawn { socket.run } + yield socket, signals + ensure + socket.try &.close + end + + private def self.domain_join(socket : HTTP::WebSocket, signals : Channel(SessionSignal), session_id : String, display_id : String) : SessionSignal + socket.send(SessionSignal.new(id: UUID.random.to_s, type: :join, session_id: session_id, user_id: display_id, to_user: "server", value: nil).to_json) + loop do + select + when signal = signals.receive + return signal if signal.type.participant_list? + when timeout(5.seconds) + raise "timed out waiting for domain participant list" + end + end + end + + describe "domain-scoped WebRTC" do + fixture = nil.as(Spec::Tenancy::Fixture?) + before_each { Utils::Tenancy.enforce = true } + after_each do + Utils::Tenancy.enforce = false + if cleanup = fixture + Spec::Tenancy.teardown(cleanup) + fixture = nil + end + end + + it "keeps public room lists and details inside the request host's organisation" do + f = fixture = Spec::Tenancy.build + [f.acadian.system, f.ucla.system].each do |system| + system.public = true + system.save! + end + headers = HTTP::Headers{"Host" => f.acadian.authority.domain} + response = client.get("#{WebRTC.base_route}rooms", headers: headers) + response.status_code.should eq 200 + Spec::Tenancy.ids(response.body).should eq [f.acadian.system.id] + client.get("#{WebRTC.base_route}room/#{f.ucla.system.id}", headers: headers).status_code.should eq 404 + client.get("#{WebRTC.base_route}room/#{f.acadian.system.id}", headers: headers).status_code.should eq 200 + end + + it "isolates the same client session id in two domains" do + f = fixture = Spec::Tenancy.build + shared_session = UUID.random.to_s + domain_signaller(f.acadian.user) do |socket_a, signals_a| + domain_join(socket_a, signals_a, shared_session, "participant-a") + domain_signaller(f.ucla.user) do |socket_b, signals_b| + participants = domain_join(socket_b, signals_b, shared_session, "participant-b") + Array(String).from_json(participants.value.not_nil!).should eq ["participant-b"] + end + end + end + + it "does not list a different domain's session participants" do + f = fixture = Spec::Tenancy.build + session_id = UUID.random.to_s + domain_signaller(f.ucla.user) do |socket, signals| + domain_join(socket, signals, session_id, "foreign-participant") + own = client.get("#{WebRTC.base_route}members/#{session_id}", headers: Spec::Tenancy.headers(f.ucla.user)) + Array(String).from_json(own.body).should eq ["foreign-participant"] + foreign = client.get("#{WebRTC.base_route}members/#{session_id}", headers: Spec::Tenancy.headers(f.acadian.user)) + foreign.status_code.should eq 200 + Array(String).from_json(foreign.body).should be_empty + end + end + + it "does not transfer a participant in another domain" do + f = fixture = Spec::Tenancy.build + session_id = UUID.random.to_s + domain_signaller(f.ucla.user) do |socket, signals| + domain_join(socket, signals, session_id, "foreign-transfer") + response = client.post("#{WebRTC.base_route}transfer/foreign-transfer/#{UUID.random}", headers: Spec::Tenancy.headers(f.acadian.user), body: {destination: "private"}.to_json) + response.status_code.should eq HTTP::Status::PRECONDITION_REQUIRED.code + end + end + + it "does not kick a participant in another domain" do + f = fixture = Spec::Tenancy.build + session_id = UUID.random.to_s + domain_signaller(f.ucla.user) do |socket, signals| + domain_join(socket, signals, session_id, "foreign-kick") + response = client.post("#{WebRTC.base_route}kick/foreign-kick/#{session_id}", headers: Spec::Tenancy.headers(f.acadian.user), body: {reason: "wrong domain"}.to_json) + response.status_code.should eq 404 + end + end + end +end diff --git a/spec/websocket/organisation_scope_spec.cr b/spec/websocket/organisation_scope_spec.cr index 5ebbf5fb..82b6a2bf 100644 --- a/spec/websocket/organisation_scope_spec.cr +++ b/spec/websocket/organisation_scope_spec.cr @@ -81,6 +81,7 @@ module PlaceOS::Api::WebSocket it "rechecks grants on an already open socket" do f = fixture = Spec::Tenancy.build grant = Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: Model::Permissions::Read.to_i).save! + wait_for_module_lookups(f.acadian.system.id.as(String), {"#{f.acadian.mod.resolved_name}/1" => f.acadian.mod.id.as(String)}) scoped_socket(f.ucla.admin, f.acadian.organisation.id.as(UUID)) do |socket, responses| socket.send scope_request(3_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind).to_json scope_response(responses, 3_i64).type.should eq Session::Response::Type::Success @@ -95,6 +96,7 @@ module PlaceOS::Api::WebSocket it "allows read-only OAuth scopes to bind while refusing execution on the same socket" do f = fixture = Spec::Tenancy.build scopes = [Model::UserJWT::Scope.new("control", Model::UserJWT::Scope::Access::Read)] + wait_for_module_lookups(f.acadian.system.id.as(String), {"#{f.acadian.mod.resolved_name}/1" => f.acadian.mod.id.as(String)}) scoped_socket(f.acadian.admin, f.acadian.organisation.id.as(UUID), scopes) do |socket, responses| socket.send scope_request(6_i64, f.acadian.system, f.acadian.mod.resolved_name, :bind).to_json scope_response(responses, 6_i64).type.should eq Session::Response::Type::Success @@ -124,9 +126,9 @@ module PlaceOS::Api::WebSocket end grant.destroy storage["live_scope"] = 200 - deadline = Time.monotonic + 500.milliseconds + deadline = Time.instant + 500.milliseconds loop do - remaining = deadline - Time.monotonic + remaining = deadline - Time.instant break if remaining <= Time::Span.zero select when response = responses.receive @@ -138,6 +140,30 @@ module PlaceOS::Api::WebSocket end end + it "does not ignore a revoked API key because its scope includes guest" do + f = fixture = Spec::Tenancy.build + key = Model::ApiKey.new(name: "Guest-marked key #{random_name}", scopes: [Model::UserJWT::Scope::PUBLIC, Model::UserJWT::Scope::GUEST]) + key.user = f.acadian.admin + key.save! + policy = Utils::Tenancy::Policy.new(key.build_jwt, f.acadian.authority.id.as(String), f.acadian.organisation.id, key.id.as(String)) + policy.system_access?(f.acadian.system.id.as(String), Model::Permissions::Read).should be_true + key.destroy + policy.system_access?(f.acadian.system.id.as(String), Model::Permissions::Read).should be_false + end + + it "uses an API key's real lifetime rather than its synthetic JWT expiry" do + f = fixture = Spec::Tenancy.build + key = Model::ApiKey.new(name: "Persistent key #{random_name}") + key.user = f.acadian.admin + key.save! + original = key.build_jwt + token = Model::UserJWT.new(iss: original.iss, iat: original.iat, exp: 1.second.ago, domain: original.domain, id: original.id, user: original.user, scope: original.scope) + policy = Utils::Tenancy::Policy.new(token, f.acadian.authority.id.as(String), f.acadian.organisation.id, key.id.as(String)) + policy.system_access?(f.acadian.system.id.as(String), Model::Permissions::Read).should be_true + key.destroy + policy.system_access?(f.acadian.system.id.as(String), Model::Permissions::Read).should be_false + end + it "does not turn a read grant into execution through the caller's home admin flag" do f = fixture = Spec::Tenancy.build Model::Grant.new(user_id: f.ucla.admin.id.as(String), scope_type: "organisation", scope_id: f.acadian.organisation.id.to_s, permissions: Model::Permissions::Read.to_i).save! diff --git a/src/placeos-rest-api/controllers/alert_dashboards.cr b/src/placeos-rest-api/controllers/alert_dashboards.cr index 42dff401..811399eb 100644 --- a/src/placeos-rest-api/controllers/alert_dashboards.cr +++ b/src/placeos-rest-api/controllers/alert_dashboards.cr @@ -15,9 +15,9 @@ module PlaceOS::Api ############################################################################################### - @[AC::Route::Filter(:before_action)] + @[AC::Route::Filter(:before_action, only: [:create])] def check_authority - unless @authority = current_authority + unless @authority = resource_authority Log.warn { {message: "authority not found", action: "authorize!", host: request.hostname} } raise Error::Unauthorized.new "authority not found" end @@ -30,6 +30,7 @@ module PlaceOS::Api Log.context.set(alert_dashboard_id: id) # Find will raise a 404 (not found) if there is an error @current_alert_dashboard = ::PlaceOS::Model::AlertDashboard.find!(id) + @authority = Utils::Tenancy.enforce? ? authority_for_resource!(current_alert_dashboard.authority_id, "dashboard") : current_authority end getter! current_alert_dashboard : ::PlaceOS::Model::AlertDashboard @@ -45,11 +46,15 @@ module PlaceOS::Api # PG full-text search (PPT-2644) query = ::PlaceOS::Model::AlertDashboard.all + if Utils::Tenancy.enforce? + query = scope_authorities(query) + ensure_authority_reach!(authority_id, "dashboard") if authority_id + end if authority_id query = query.where(authority_id: authority_id) - elsif !user_support? + elsif !Utils::Tenancy.enforce? && !user_support? # Limit to current authority for non-support users - query = query.where(authority_id: authority.id.as(String)) + query = query.where(authority_id: resource_authority!.id.as(String)) end paginate_search(query, ::PlaceOS::Model::AlertDashboard.table_name) @@ -67,7 +72,13 @@ module PlaceOS::Api @[AC::Route::PUT("/:id", body: :dashboard)] def update(dashboard : ::PlaceOS::Model::AlertDashboard) : ::PlaceOS::Model::AlertDashboard current = current_alert_dashboard + owner = current.authority_id + if Utils::Tenancy.enforce? && (requested = dashboard.authority_id) && requested != owner + ensure_resource_authority!(requested, "dashboard") + raise Error::Forbidden.new("dashboard ownership cannot be reassigned") + end current.assign_attributes(dashboard) + current.authority_id = owner if Utils::Tenancy.enforce? raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -80,6 +91,7 @@ module PlaceOS::Api dashboard.authority_id = authority.id end + ensure_resource_authority!(dashboard.authority_id, "dashboard") raise Error::ModelValidation.new(dashboard.errors) unless dashboard.save dashboard end diff --git a/src/placeos-rest-api/controllers/alerts.cr b/src/placeos-rest-api/controllers/alerts.cr index c82fab8a..abef8229 100644 --- a/src/placeos-rest-api/controllers/alerts.cr +++ b/src/placeos-rest-api/controllers/alerts.cr @@ -20,6 +20,7 @@ module PlaceOS::Api Log.context.set(alert_id: id) # Find will raise a 404 (not found) if there is an error @current_alert = ::PlaceOS::Model::Alert.find!(id) + check_alert_dashboard(current_alert) end getter! current_alert : ::PlaceOS::Model::Alert @@ -46,12 +47,23 @@ module PlaceOS::Api ) : Array(::PlaceOS::Model::Alert) # PG full-text search (PPT-2644) query = ::PlaceOS::Model::Alert.all + if Utils::Tenancy.enforce? + dashboards = scope_authorities(::PlaceOS::Model::AlertDashboard.all).to_a.compact_map(&.id) + if dashboards.empty? + set_collection_headers(0, ::PlaceOS::Model::Alert.table_name) + return [] of ::PlaceOS::Model::Alert + end + query = query.where(alert_dashboard_id: dashboards) + end if adi = alert_dashboard_id + if Utils::Tenancy.enforce? + ensure_resource_authority!(::PlaceOS::Model::AlertDashboard.find!(adi).authority_id, "dashboard") + end query = query.where(alert_dashboard_id: adi) - elsif !user_support? + elsif !Utils::Tenancy.enforce? && !user_support? # Limit to current authority's dashboards for non-support users - auth = current_authority.as(::PlaceOS::Model::Authority) + auth = resource_authority! dashboard_ids = ::PlaceOS::Model::AlertDashboard.where(authority_id: auth.id).select(:id).map(&.id.as(String)) if dashboard_ids.empty? set_collection_headers(0, ::PlaceOS::Model::Alert.table_name) @@ -110,6 +122,7 @@ module PlaceOS::Api def update(alert : ::PlaceOS::Model::Alert) : ::PlaceOS::Model::Alert current = current_alert current.assign_attributes(alert) + check_alert_dashboard(current) raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -117,10 +130,11 @@ module PlaceOS::Api # adds a new alert @[AC::Route::POST("/", body: :alert, status_code: HTTP::Status::CREATED)] def create(alert : ::PlaceOS::Model::Alert) : ::PlaceOS::Model::Alert + check_alert_dashboard(alert) # Validate that the dashboard belongs to the current authority if not support user if alert.alert_dashboard_id && !user_support? dashboard = ::PlaceOS::Model::AlertDashboard.find!(alert.alert_dashboard_id.as(String)) - auth = current_authority.as(::PlaceOS::Model::Authority) + auth = resource_authority! unless dashboard.authority_id == auth.id raise Error::Forbidden.new("Cannot create alert for dashboard in different authority") end @@ -130,6 +144,13 @@ module PlaceOS::Api alert end + private def check_alert_dashboard(alert : ::PlaceOS::Model::Alert) + return unless Utils::Tenancy.enforce? + if id = alert.alert_dashboard_id + authority_for_resource!(::PlaceOS::Model::AlertDashboard.find!(id).authority_id, "dashboard") + end + end + # removes an alert @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] def destroy : Nil diff --git a/src/placeos-rest-api/controllers/api_keys.cr b/src/placeos-rest-api/controllers/api_keys.cr index b436bfb9..a8f94342 100644 --- a/src/placeos-rest-api/controllers/api_keys.cr +++ b/src/placeos-rest-api/controllers/api_keys.cr @@ -105,7 +105,17 @@ module PlaceOS::Api @[AC::Route::PUT("/:id", body: :api_key)] def update(api_key : ::PlaceOS::Model::ApiKey) : Response current = current_api_key + original_authority = current.authority_id current.assign_attributes(api_key) + owner = ::PlaceOS::Model::User.find!(current.user_id.as(String)) + ensure_authority_reach!(owner.authority_id, "user") + ensure_authority_reach!(current.authority_id, "domain") + if api_key.permissions_assigned? || api_key.scopes_assigned? || api_key.user_id_assigned? || api_key.authority_id_assigned? + ensure_credential_management!(original_authority) + end + if Utils::Tenancy.enforce? && (current.authority_id != original_authority || owner.authority_id != original_authority) + raise Error::ModelValidation.new([Utils::Tenancy::Failure.new(:user_id, "user must belong to the key's original domain")]) + end raise Error::ModelValidation.new(current.errors) unless current.save Response.new(current) end @@ -114,7 +124,9 @@ module PlaceOS::Api @[AC::Route::POST("/", body: :api_key, status_code: HTTP::Status::CREATED)] def create(api_key : ::PlaceOS::Model::ApiKey) : Response if user_id = api_key.user_id - ensure_authority_reach!(::PlaceOS::Model::User.find!(user_id).authority_id, "user") + owner_authority = ::PlaceOS::Model::User.find!(user_id).authority_id + ensure_authority_reach!(owner_authority, "user") + ensure_credential_management!(owner_authority) end raise Error::ModelValidation.new(api_key.errors) unless api_key.save Response.new(api_key) diff --git a/src/placeos-rest-api/controllers/application.cr b/src/placeos-rest-api/controllers/application.cr index 3dcec77b..971d53d3 100644 --- a/src/placeos-rest-api/controllers/application.cr +++ b/src/placeos-rest-api/controllers/application.cr @@ -40,6 +40,8 @@ module PlaceOS::Api # Helpers for organisation reach (PPT-526 multi-tenancy) include Utils::Tenancy + include Utils::ResourceAuthority + include Utils::HistoryScope # for converting comma seperated lists # i.e. `"id-1,id-2,id-3"`, or a JSON array `["id-1","id-2"]` @@ -174,6 +176,16 @@ module PlaceOS::Api # Simplifies determining user's requests in server-side logs before_action :set_user_id + @[AC::Route::Filter(:before_action)] + def resolve_organisation_context( + @[AC::Param::Info(description: "organisation selected for this REST request; ordinary callers default to their home organisation", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + organisation_id : UUID? = nil, + @[AC::Param::Info(description: "target domain when an organisation has multiple domains", example: "auth-12345")] + authority_id : String? = nil, + ) + prepare_organisation_selection(organisation_id, authority_id) + end + def set_user_id Log.context.set(user_id: user_token.id) end @@ -243,6 +255,16 @@ module PlaceOS::Api end end + record OrganisationSelectionError, error : String, code : String do + include JSON::Serializable + include YAML::Serializable + end + + @[AC::Route::Exception(Error::OrganisationSelection, status_code: HTTP::Status::BAD_REQUEST)] + def invalid_organisation_selection(error) : OrganisationSelectionError + OrganisationSelectionError.new(error.message || "invalid organisation selection", error.code) + end + # CONFLICT if there is a version clash @[AC::Route::Exception(Error::Conflict, status_code: HTTP::Status::CONFLICT)] def resource_conflict(error) : CommonError diff --git a/src/placeos-rest-api/controllers/asset_categories.cr b/src/placeos-rest-api/controllers/asset_categories.cr index 793789d9..d3a7a639 100644 --- a/src/placeos-rest-api/controllers/asset_categories.cr +++ b/src/placeos-rest-api/controllers/asset_categories.cr @@ -18,7 +18,7 @@ module PlaceOS::Api private def confirm_access return if user_support? - authority = current_authority.as(::PlaceOS::Model::Authority) + authority = resource_authority! if zone_id = authority.config["org_zone"]?.try(&.as_s?) # "support" subsystem: the verb's bit on the org zone. @@ -37,6 +37,7 @@ module PlaceOS::Api Log.context.set(asset_category_id: id) # Find will raise a 404 (not found) if there is an error @current_asset_category = ::PlaceOS::Model::AssetCategory.find!(id) + authority_for_resource!(current_asset_category.authority_id, "asset category") if Utils::Tenancy.enforce? end getter! current_asset_category : ::PlaceOS::Model::AssetCategory @@ -46,7 +47,11 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:show])] private def confirm_authority owner = current_asset_category.authority_id - return if owner.nil? || owner == current_authority.as(::PlaceOS::Model::Authority).id + if Utils::Tenancy.enforce? + authority_for_resource!(owner, "asset category") + return + end + return if owner.nil? || owner == resource_authority!.id raise Error::NotFound.new("asset category #{current_asset_category.id} not found") end @@ -61,7 +66,7 @@ module PlaceOS::Api ) : Array(::PlaceOS::Model::AssetCategory) # PG full-text search (PPT-2644) query = ::PlaceOS::Model::AssetCategory.all - query = query.where("authority_id IS NULL OR authority_id = ?", current_authority.as(::PlaceOS::Model::Authority).id) + query = query.where("authority_id = ? OR (authority_id IS NULL AND #{!Utils::Tenancy.enforce?})", resource_authority!.id) # NOTE:: the Elasticsearch implementation silently skipped this filter # when `hidden=false` (Crystal falsy), contradicting the documented @@ -84,7 +89,7 @@ module PlaceOS::Api @[AC::Route::PUT("/:id", body: :asset_category)] def update(asset_category : ::PlaceOS::Model::AssetCategory) : ::PlaceOS::Model::AssetCategory current = current_asset_category - authority_id = current_authority.as(::PlaceOS::Model::Authority).id + authority_id = resource_authority!.id # A category that already belongs to another authority may not be edited. # Legacy records with no authority get adopted by the current authority. @@ -94,6 +99,7 @@ module PlaceOS::Api current.assign_attributes(asset_category) current.authority_id = authority_id + check_category_parent(current) raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -101,17 +107,25 @@ module PlaceOS::Api # Create an asset category. @[AC::Route::POST("/", body: :asset_category, status_code: HTTP::Status::CREATED)] def create(asset_category : ::PlaceOS::Model::AssetCategory) : ::PlaceOS::Model::AssetCategory - asset_category.authority_id = current_authority.as(::PlaceOS::Model::Authority).id + asset_category.authority_id = resource_authority!.id + check_category_parent(asset_category) raise Error::ModelValidation.new(asset_category.errors) unless asset_category.save asset_category end + private def check_category_parent(category : ::PlaceOS::Model::AssetCategory) + return unless Utils::Tenancy.enforce? + if id = category.parent_category_id + ensure_resource_authority!(::PlaceOS::Model::AssetCategory.find!(id).authority_id, "parent category") + end + end + # Delete an asset category. @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] def destroy : Nil # A category owned by another authority may not be removed (same guard # as update; legacy records with no authority remain removable). - authority_id = current_authority.as(::PlaceOS::Model::Authority).id + authority_id = resource_authority!.id if (existing = current_asset_category.authority_id) && existing != authority_id raise Error::Forbidden.new("asset category belongs to another authority") end diff --git a/src/placeos-rest-api/controllers/asset_purchase_orders.cr b/src/placeos-rest-api/controllers/asset_purchase_orders.cr index 91ca16ef..28ef0d1b 100644 --- a/src/placeos-rest-api/controllers/asset_purchase_orders.cr +++ b/src/placeos-rest-api/controllers/asset_purchase_orders.cr @@ -18,7 +18,7 @@ module PlaceOS::Api private def confirm_access return if user_support? - authority = current_authority.as(::PlaceOS::Model::Authority) + authority = resource_authority! if zone_id = authority.config["org_zone"]?.try(&.as_s?) # "support" subsystem: Read on the org zone for GET (index/show), @@ -40,6 +40,7 @@ module PlaceOS::Api Log.context.set(asset_purchase_order_id: id) # Find will raise a 404 (not found) if there is an error @current_asset_purchase_order = ::PlaceOS::Model::AssetPurchaseOrder.find!(id) + authority_for_resource!(current_asset_purchase_order.authority_id, "asset purchase order") if Utils::Tenancy.enforce? end getter! current_asset_purchase_order : ::PlaceOS::Model::AssetPurchaseOrder @@ -47,7 +48,7 @@ module PlaceOS::Api # 404 unless the purchase order belongs to the caller's authority, for admin and support users too. @[AC::Route::Filter(:before_action, only: [:show, :update, :destroy])] private def confirm_authority - return if current_asset_purchase_order.authority_id == current_authority.as(::PlaceOS::Model::Authority).id + return if current_asset_purchase_order.authority_id == resource_authority!.id raise Error::NotFound.new("asset purchase order #{current_asset_purchase_order.id} not found") end @@ -60,7 +61,7 @@ module PlaceOS::Api # invoice_number. The table has no name column so order by PO number # for a deterministic listing (Elasticsearch had no explicit sort here). query = ::PlaceOS::Model::AssetPurchaseOrder.all - query = query.where(authority_id: current_authority.as(::PlaceOS::Model::Authority).id) + query = query.where(authority_id: resource_authority!.id) paginate_search( query, ::PlaceOS::Model::AssetPurchaseOrder.table_name, @@ -89,7 +90,7 @@ module PlaceOS::Api # Create an asset purchase order. @[AC::Route::POST("/", body: :asset_purchase_order, status_code: HTTP::Status::CREATED)] def create(asset_purchase_order : ::PlaceOS::Model::AssetPurchaseOrder) : ::PlaceOS::Model::AssetPurchaseOrder - asset_purchase_order.authority_id = current_authority.as(::PlaceOS::Model::Authority).id + asset_purchase_order.authority_id = resource_authority!.id raise Error::ModelValidation.new(asset_purchase_order.errors) unless asset_purchase_order.save asset_purchase_order end diff --git a/src/placeos-rest-api/controllers/asset_types.cr b/src/placeos-rest-api/controllers/asset_types.cr index c0071390..dd4f5ae0 100644 --- a/src/placeos-rest-api/controllers/asset_types.cr +++ b/src/placeos-rest-api/controllers/asset_types.cr @@ -18,7 +18,7 @@ module PlaceOS::Api private def confirm_access return if user_support? - authority = current_authority.as(::PlaceOS::Model::Authority) + authority = resource_authority! if zone_id = authority.config["org_zone"]?.try(&.as_s?) # "support" subsystem: the verb's bit on the org zone. @@ -49,7 +49,11 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:show, :update, :destroy])] private def confirm_authority owner = current_asset_type.category.try(&.authority_id) - return if owner.nil? || owner == current_authority.as(::PlaceOS::Model::Authority).id + if Utils::Tenancy.enforce? + authority_for_resource!(owner, "asset type") + return + end + return if owner.nil? || owner == resource_authority!.id raise Error::NotFound.new("asset type #{current_asset_type.id} not found") end @@ -74,8 +78,8 @@ module PlaceOS::Api # Callers only see asset types belonging to their own authority (via the # category); legacy NULL-authority categories stay visible (see # `confirm_authority`). - args << current_authority.as(::PlaceOS::Model::Authority).id - where_clauses << "EXISTS (SELECT 1 FROM asset_category ac WHERE ac.id = at.category_id AND (ac.authority_id IS NULL OR ac.authority_id = $#{args.size}))" + args << resource_authority!.id + where_clauses << "EXISTS (SELECT 1 FROM asset_category ac WHERE ac.id = at.category_id AND (ac.authority_id = $#{args.size} OR (ac.authority_id IS NULL AND #{!Utils::Tenancy.enforce?})))" if brand args << brand @@ -161,6 +165,7 @@ module PlaceOS::Api def update(asset_type : ::PlaceOS::Model::AssetType) : ::PlaceOS::Model::AssetType current = current_asset_type current.assign_attributes(asset_type) + check_type_category(current) raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -168,10 +173,18 @@ module PlaceOS::Api # Create an asset type. @[AC::Route::POST("/", body: :asset_type, status_code: HTTP::Status::CREATED)] def create(asset_type : ::PlaceOS::Model::AssetType) : ::PlaceOS::Model::AssetType + check_type_category(asset_type) raise Error::ModelValidation.new(asset_type.errors) unless asset_type.save asset_type end + private def check_type_category(type : ::PlaceOS::Model::AssetType) + return unless Utils::Tenancy.enforce? + if id = type.category_id + ensure_resource_authority!(::PlaceOS::Model::AssetCategory.find!(id).authority_id, "asset category") + end + end + # Delete an asset type. @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] def destroy : Nil diff --git a/src/placeos-rest-api/controllers/assets.cr b/src/placeos-rest-api/controllers/assets.cr index 965098bd..651c3b90 100644 --- a/src/placeos-rest-api/controllers/assets.cr +++ b/src/placeos-rest-api/controllers/assets.cr @@ -39,6 +39,12 @@ module PlaceOS::Api # a new or changed asset may only use an asset type of the caller's authority private def confirm_asset_type_authority(asset : ::PlaceOS::Model::Asset) raise Error::Forbidden.new("asset type #{asset.asset_type_id} belongs to another authority") unless owned_by_caller?(asset) + if Utils::Tenancy.enforce? + ([asset.zone_id] + asset.zones).compact.uniq!.each { |id| ensure_reach!(::PlaceOS::Model::Zone.find!(id)) } + if order_id = asset.purchase_order_id + ensure_resource_authority!(::PlaceOS::Model::AssetPurchaseOrder.find!(order_id).authority_id, "asset purchase order") + end + end end # whether the asset's type belongs to the caller's authority (or to a legacy category with no @@ -47,7 +53,11 @@ module PlaceOS::Api private def owned_by_caller?(asset : ::PlaceOS::Model::Asset) : Bool asset_type = asset.asset_type_id.try { |type_id| ::PlaceOS::Model::AssetType.find?(type_id) } owner = asset_type.try(&.category).try(&.authority_id) - owner.nil? || owner == current_authority.as(::PlaceOS::Model::Authority).id + if Utils::Tenancy.enforce? + authority_for_resource!(owner, "asset") + return true + end + owner.nil? || owner == resource_authority!.id end @[AC::Route::Filter(:before_action, only: [:update, :destroy])] @@ -58,7 +68,7 @@ module PlaceOS::Api asset_zones = ([current_asset.zone_id] + current_asset.zones).compact.uniq! return if support_subsystem_grants?(asset_zones, verb_permission) - authority = current_authority.as(::PlaceOS::Model::Authority) + authority = resource_authority! if zone_id = authority.config["org_zone"]?.try(&.as_s?) zones = [zone_id, current_asset.zone_id].compact @@ -99,9 +109,9 @@ module PlaceOS::Api # Callers only see assets belonging to their own authority (via # asset_type → category); legacy NULL-authority categories stay visible # (see `confirm_authority`). - authority_id = current_authority.as(::PlaceOS::Model::Authority).id + authority_id = resource_authority!.id query = query.where( - "EXISTS (SELECT 1 FROM asset_type at JOIN asset_category ac ON ac.id = at.category_id WHERE at.id = asset.asset_type_id AND (ac.authority_id IS NULL OR ac.authority_id = ?))", + "EXISTS (SELECT 1 FROM asset_type at JOIN asset_category ac ON ac.id = at.category_id WHERE at.id = asset.asset_type_id AND (ac.authority_id = ? OR (ac.authority_id IS NULL AND #{!Utils::Tenancy.enforce?})))", authority_id ) @@ -205,42 +215,52 @@ module PlaceOS::Api # Create several assets; the body is a JSON array of assets. @[AC::Route::POST("/bulk", body: :assets, status_code: HTTP::Status::CREATED)] def bulk_create(assets : Array(::PlaceOS::Model::Asset)) : Array(::PlaceOS::Model::Asset) - assets.map do |asset| - @current_asset = asset - confirm_asset_type_authority(asset) - confirm_access - raise Error::ModelValidation.new(asset.errors) unless asset.save - asset + results = [] of ::PlaceOS::Model::Asset + PgORM::Database.transaction do |_transaction| + results = assets.map do |asset| + @current_asset = asset + confirm_asset_type_authority(asset) + confirm_access + raise Error::ModelValidation.new(asset.errors) unless asset.save + asset + end end + results end # Update several assets; the body is a JSON array of assets, each with its `id`. @[AC::Route::PATCH("/bulk", body: :assets)] @[AC::Route::PUT("/bulk", body: :assets)] def bulk_update(assets : Array(::PlaceOS::Model::Asset)) : Array(::PlaceOS::Model::Asset) - assets.compact_map do |asset| - if asset_id = asset.id - current = find_current_asset(asset_id) - confirm_authority - confirm_access - current.assign_attributes(asset) - confirm_asset_type_authority(current) - # destination zones of a move must be authorised too - confirm_access - raise Error::ModelValidation.new(current.errors) unless current.save - current + results = [] of ::PlaceOS::Model::Asset + PgORM::Database.transaction do |_transaction| + results = assets.compact_map do |asset| + if asset_id = asset.id + current = find_current_asset(asset_id) + confirm_authority + confirm_access + current.assign_attributes(asset) + confirm_asset_type_authority(current) + # destination zones of a move must be authorised too + confirm_access + raise Error::ModelValidation.new(current.errors) unless current.save + current + end end end + results end # Delete several assets; the body is a JSON array of asset ids. @[AC::Route::DELETE("/bulk", body: :asset_ids, status_code: HTTP::Status::ACCEPTED)] def bulk_destroy(asset_ids : Array(String)) : Nil - asset_ids.each do |asset_id| - current = find_current_asset(asset_id) - confirm_authority - confirm_access - current.destroy + PgORM::Database.transaction do |_transaction| + asset_ids.each do |asset_id| + current = find_current_asset(asset_id) + confirm_authority + confirm_access + current.destroy + end end end end diff --git a/src/placeos-rest-api/controllers/authentications.cr b/src/placeos-rest-api/controllers/authentications.cr index a7ac9e63..71cde069 100644 --- a/src/placeos-rest-api/controllers/authentications.cr +++ b/src/placeos-rest-api/controllers/authentications.cr @@ -24,6 +24,8 @@ module PlaceOS::Api # Find will raise a 404 (not found) if there is an error auth = ::PlaceOS::Model::{{auth_type.id}}Authentication.find!(id) ensure_authority_reach!(auth.authority_id, "authentication") + ensure_credential_management!(auth.authority_id) + ensure_credential_management!(auth.authority_id) @current_auth = auth end @@ -38,7 +40,7 @@ module PlaceOS::Api authority_id : String? = nil, ) : Array(::PlaceOS::Model::{{auth_type.id}}Authentication) # PG full-text search (PPT-2644) - query = scope_authorities(::PlaceOS::Model::{{auth_type.id}}Authentication.all) + query = scope_authorities(::PlaceOS::Model::{{auth_type.id}}Authentication.all, required: Utils::Tenancy.enforce? ? ::PlaceOS::Model::Permissions::Manage : tenancy_permission) if authority = authority_id ensure_authority_reach!(authority, "domain") @@ -59,7 +61,13 @@ module PlaceOS::Api @[AC::Route::PUT("/:id", body: :auth)] def update(auth : ::PlaceOS::Model::{{auth_type.id}}Authentication) : ::PlaceOS::Model::{{auth_type.id}}Authentication current = current_auth + owner = current.authority_id current.assign_attributes(auth) + ensure_authority_reach!(current.authority_id, "authentication") + ensure_credential_management!(current.authority_id) + if Utils::Tenancy.enforce? && current.authority_id != owner + raise Error::ModelValidation.new([Utils::Tenancy::Failure.new(:authority_id, "authentication ownership cannot be changed")]) + end raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -68,6 +76,7 @@ module PlaceOS::Api @[AC::Route::POST("/", body: :auth, status_code: HTTP::Status::CREATED)] def create(auth : ::PlaceOS::Model::{{auth_type.id}}Authentication) : ::PlaceOS::Model::{{auth_type.id}}Authentication ensure_authority_reach!(auth.authority_id, "domain") + ensure_credential_management!(auth.authority_id) raise Error::ModelValidation.new(auth.errors) unless auth.save auth end diff --git a/src/placeos-rest-api/controllers/chat_gpt.cr b/src/placeos-rest-api/controllers/chat_gpt.cr index 2914ebe5..c8fc411b 100644 --- a/src/placeos-rest-api/controllers/chat_gpt.cr +++ b/src/placeos-rest-api/controllers/chat_gpt.cr @@ -13,7 +13,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action)] def check_authority - unless @authority = current_authority + unless @authority = resource_authority Log.warn { {message: "authority not found", action: "authorize!", host: request.hostname} } raise Error::Unauthorized.new "authority not found" end @@ -25,7 +25,13 @@ module PlaceOS::Api # list user chats @[AC::Route::GET("/")] def index : Array(::PlaceOS::Model::Chat) - ::PlaceOS::Model::Chat.where(user_id: current_user.id.not_nil!).all.to_a + query = ::PlaceOS::Model::Chat.where(user_id: current_user.id.not_nil!) + if Utils::Tenancy.enforce? + ids = scope_organisations(::PlaceOS::Model::ControlSystem.all).to_a.compact_map(&.id) + return [] of ::PlaceOS::Model::Chat if ids.empty? + query = query.where(system_id: ids) + end + query.to_a end # show user chat history @@ -45,6 +51,9 @@ module PlaceOS::Api # lagging replica, which would 404 and spawn a duplicate chat. @[AC::Route::Filter(:before_action, only: [:chat])] def find_resume_chat(resume : String? = nil) + if Utils::Tenancy.enforce? + ensure_reach!(::PlaceOS::Model::ControlSystem.find!(route_params["system_id"])) + end @resume_chat = on_primary { own_chat!(resume) } if resume end @@ -84,6 +93,7 @@ module PlaceOS::Api Log.warn { {message: "Invalid chat id. Unable to find matching chat for user", id: id, user: current_user.id} } raise Error::NotFound.new("Invalid chat id: #{id}") end + ensure_reach!(::PlaceOS::Model::ControlSystem.find!(chat.system_id)) if Utils::Tenancy.enforce? chat end diff --git a/src/placeos-rest-api/controllers/chat_gpt/plugins.cr b/src/placeos-rest-api/controllers/chat_gpt/plugins.cr index b2fde4d8..75ec3be6 100644 --- a/src/placeos-rest-api/controllers/chat_gpt/plugins.cr +++ b/src/placeos-rest-api/controllers/chat_gpt/plugins.cr @@ -21,7 +21,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action)] def check_authority - unless @authority = current_authority + unless @authority = resource_authority Log.warn { {message: "authority not found", action: "authorize!", host: request.hostname} } raise Error::Unauthorized.new "authority not found" end @@ -31,6 +31,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action)] def find_control_system @control_system = ::PlaceOS::Model::ControlSystem.find!(system_id) + ensure_reach!(control_system) end getter! authority : ::PlaceOS::Model::Authority? diff --git a/src/placeos-rest-api/controllers/domains.cr b/src/placeos-rest-api/controllers/domains.cr index c5647e82..49590667 100644 --- a/src/placeos-rest-api/controllers/domains.cr +++ b/src/placeos-rest-api/controllers/domains.cr @@ -5,6 +5,39 @@ module PlaceOS::Api class Domains < Application base "/api/engine/v2/domains/" + # Delegated reads do not expose authentication secrets in internals. + struct ReadOnlyDomain + include JSON::Serializable + include YAML::Serializable + + getter id : String? + getter name : String + getter description : String + getter domain : String + getter login_url : String + getter logout_url : String + getter config : Hash(String, JSON::Any) + getter email_domains : Array(String) + getter organisation_id : UUID? + @[JSON::Field(converter: PlaceOS::Model::Timestamps::EpochConverter, type: "integer", format: "Int64")] + getter created_at : Time + @[JSON::Field(converter: PlaceOS::Model::Timestamps::EpochConverter, type: "integer", format: "Int64")] + getter updated_at : Time + + def initialize(authority : ::PlaceOS::Model::Authority) + @id, @name, @description, @domain = authority.id, authority.name, authority.description, authority.domain + @login_url, @logout_url, @config = authority.login_url, authority.logout_url, authority.config + @email_domains, @organisation_id = authority.email_domains, authority.organisation_id + @created_at, @updated_at = authority.created_at, authority.updated_at + end + end + + alias DomainView = ::PlaceOS::Model::Authority | ReadOnlyDomain + + private def domain_view(authority : ::PlaceOS::Model::Authority) : DomainView + may_manage_authority?(authority.id) ? authority : ReadOnlyDomain.new(authority) + end + # Scopes ############################################################################################### @@ -34,10 +67,10 @@ module PlaceOS::Api def index( @[AC::Param::Info(description: "only rows owned by this organisation (must be within reach)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] organisation_id : UUID? = nil, - ) : Array(::PlaceOS::Model::Authority) + ) : Array(DomainView) # PG full-text search (PPT-2644) - query = narrow_organisation(scope_organisations(::PlaceOS::Model::Authority.all), organisation_id) - paginate_search(query, ::PlaceOS::Model::Authority.table_name) + query = narrow_organisation(scope_authorities(::PlaceOS::Model::Authority.all, "id"), organisation_id) + paginate_search(query, ::PlaceOS::Model::Authority.table_name).map { |authority| domain_view(authority) } end # skip authentication for the lookup @@ -58,8 +91,8 @@ module PlaceOS::Api # show the selected domain @[AC::Route::GET("/:id")] - def show : ::PlaceOS::Model::Authority - current_domain + def show : DomainView + domain_view(current_domain) end # udpate a domains details @@ -67,12 +100,15 @@ module PlaceOS::Api @[AC::Route::PUT("/:id", body: :domain)] def update( domain : ::PlaceOS::Model::Authority, - @[AC::Param::Info(description: "move the domain to this organisation (cluster admins only)", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] + @[AC::Param::Info(description: "the selected organisation; ownership cannot be changed while tenancy is enforced", example: "0192f1c4-7a6b-7c4d-9f3e-1a2b3c4d5e6f")] organisation_id : UUID? = nil, ) : ::PlaceOS::Model::Authority current = current_domain + if domain.internals_assigned? || domain.domain_assigned? || domain.email_domains_assigned? || domain.login_url_assigned? || domain.logout_url_assigned? + ensure_credential_management!(current.id) + end current.assign_attributes(domain) - if organisation_id + if organisation_id && !Utils::Tenancy.enforce? check_cluster_admin current.organisation_id = organisation_id end @@ -89,6 +125,7 @@ module PlaceOS::Api organisation_id : UUID? = nil, ) : ::PlaceOS::Model::Authority domain.organisation_id = organisation_for_new_row(organisation_id) + ensure_reach!(domain.organisation_id, "organisation", required: ::PlaceOS::Model::Permissions::Manage) raise Error::ModelValidation.new(domain.errors) unless domain.save domain end @@ -96,6 +133,7 @@ module PlaceOS::Api # remove a domain @[AC::Route::DELETE("/:id", status_code: HTTP::Status::ACCEPTED)] def destroy : Nil + ensure_credential_management!(current_domain.id) current_domain.destroy end end diff --git a/src/placeos-rest-api/controllers/edges.cr b/src/placeos-rest-api/controllers/edges.cr index fc49cd07..7eaa3665 100644 --- a/src/placeos-rest-api/controllers/edges.cr +++ b/src/placeos-rest-api/controllers/edges.cr @@ -94,6 +94,10 @@ module PlaceOS::Api def update(edge : ::PlaceOS::Model::Edge) : ::PlaceOS::Model::Edge current = current_edge current.assign_attributes(edge) + if current.user_id + owner = ::PlaceOS::Model::User.find!(current.user_id.as(String)) + ensure_authority_reach!(owner.authority_id, "user") + end raise Error::ModelValidation.new(current.errors) unless current.save current end diff --git a/src/placeos-rest-api/controllers/flux.cr b/src/placeos-rest-api/controllers/flux.cr index 69e47ea8..8ba85680 100644 --- a/src/placeos-rest-api/controllers/flux.cr +++ b/src/placeos-rest-api/controllers/flux.cr @@ -11,6 +11,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action)] def deny_guests raise Error::Forbidden.new("guest tokens may not query flux") if user_token.guest_scope? + check_cluster_admin if Utils::Tenancy.enforce? end # an influxDB proxy endpoint, route compatible with existing influxDB clients diff --git a/src/placeos-rest-api/controllers/grants.cr b/src/placeos-rest-api/controllers/grants.cr index 63be43d5..23c5e556 100644 --- a/src/placeos-rest-api/controllers/grants.cr +++ b/src/placeos-rest-api/controllers/grants.cr @@ -32,8 +32,8 @@ module PlaceOS::Api # into their own organisation and its domains; partner admins request # rather than self-grant protected def ensure_scope_reach!(scope_type : String, scope_id : String) : Nil - return if tenancy.cluster? - own = tenancy.organisation_id + return if accessible_tenancy.cluster? + own = accessible_tenancy.organisation_id allowed = case scope_type when ::PlaceOS::Model::Grant::SCOPE_ORGANISATION own && own.to_s == scope_id diff --git a/src/placeos-rest-api/controllers/groups.cr b/src/placeos-rest-api/controllers/groups.cr index b9354304..edd7ada1 100644 --- a/src/placeos-rest-api/controllers/groups.cr +++ b/src/placeos-rest-api/controllers/groups.cr @@ -17,6 +17,13 @@ module PlaceOS::Api before_action :can_write, only: [:create, :update, :destroy, :sync_ad_groups] before_action :check_support, only: [:sync_ad_groups] + private def check_group_parent(group : ::PlaceOS::Model::Group) + return unless Utils::Tenancy.enforce? + if id = group.parent_id + ensure_resource_authority!(::PlaceOS::Model::Group.find!(id).authority_id, "parent group") + end + end + # Response helpers ############################################################################################### @@ -31,6 +38,7 @@ module PlaceOS::Api def find_current_group(id : UUID) Log.context.set(group_id: id.to_s) @current_group = ::PlaceOS::Model::Group.find!(id) + authority_for_resource!(current_group.authority_id, "group") if Utils::Tenancy.enforce? end getter! current_group : ::PlaceOS::Model::Group @@ -52,6 +60,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:create])] def check_create_permissions + check_group_parent(group_update) return if user_admin? # Root groups (parent_id nil) can only be created by sys_admin. parent_id = group_update.parent_id @@ -62,6 +71,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:update])] def check_update_permissions + check_group_parent(group_update) return if user_admin? ensure_manage!(current_user, current_group) # Block reparenting unless manager also has Manage on the new parent. @@ -108,7 +118,7 @@ module PlaceOS::Api limit : Int32 = 100, offset : Int32 = 0, ) : Array(::PlaceOS::Model::Group) - authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + authority_id = resource_authority!.id.as(String) query = ::PlaceOS::Model::Group.where(authority_id: authority_id) unless user_admin? @@ -121,6 +131,9 @@ module PlaceOS::Api if parent_id == "root" query = query.where(parent_id: nil) else + if Utils::Tenancy.enforce? + ensure_resource_authority!(::PlaceOS::Model::Group.find!(UUID.new(parent_id)).authority_id, "parent group") + end query = query.where(parent_id: UUID.new(parent_id)) end end @@ -190,7 +203,13 @@ module PlaceOS::Api def update : ::PlaceOS::Model::Group update = group_update current = current_group + authority_id = current.authority_id + if Utils::Tenancy.enforce? && update.authority_id_present? && (requested = update.authority_id.presence) && requested != authority_id + ensure_resource_authority!(requested, "group") + raise Error::Forbidden.new("group ownership cannot be reassigned") + end current.assign_attributes(update) + current.authority_id = authority_id if Utils::Tenancy.enforce? raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -201,7 +220,7 @@ module PlaceOS::Api def create : ::PlaceOS::Model::Group group = group_update # Force the authority to the caller's — no cross-authority moves. - group.authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + group.authority_id = resource_authority!.id.as(String) raise Error::ModelValidation.new(group.errors) unless group.save group end @@ -227,7 +246,7 @@ module PlaceOS::Api # group memberships in the current authority. Requires support or sys_admin. @[AC::Route::POST("/ad_groups/sync", body: :sync)] def sync_ad_groups(sync : AdGroupSync) : Array(::PlaceOS::Model::GroupUser) - authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + authority_id = resource_authority!.id.as(String) user = ::PlaceOS::Model::User.find?(sync.user_id) raise Error::NotFound.new("user #{sync.user_id} not found") unless user && user.authority_id == authority_id @@ -261,7 +280,9 @@ module PlaceOS::Api memberships = group_memberships(current_user) return [] of CurrentGroup if memberships.empty? - groups = ::PlaceOS::Model::Group.where(id: memberships.keys).to_a + query = ::PlaceOS::Model::Group.where(id: memberships.keys) + query = scope_authorities(query) if Utils::Tenancy.enforce? + groups = query.to_a groups.compact_map do |g| gid = g.id next if gid.nil? diff --git a/src/placeos-rest-api/controllers/groups/history.cr b/src/placeos-rest-api/controllers/groups/history.cr index 24e5ba24..7a57ef6c 100644 --- a/src/placeos-rest-api/controllers/groups/history.cr +++ b/src/placeos-rest-api/controllers/groups/history.cr @@ -25,6 +25,7 @@ module PlaceOS::Api Log.context.set(group_history_id: id.to_s) history = ::PlaceOS::Model::History.find!(id) raise Error::NotFound.new("not a group history entry") unless history.resource_type.in?(RESOURCE_TYPES) + ensure_history_reach!(history) @current_history = history end @@ -55,6 +56,13 @@ module PlaceOS::Api @[AC::Param::Info(description: "the starting offset of the result set, used to implement pagination")] offset : Int32 = 0, ) : Array(::PlaceOS::Model::History) + if Utils::Tenancy.enforce? && group_id + if group = ::PlaceOS::Model::Group.find?(group_id) + ensure_resource_authority!(group.authority_id, "group") + elsif scope_history(::PlaceOS::Model::History.correlated(group_id.to_s)).count == 0 + raise Error::NotFound.new("group not found") + end + end unless user_admin? # Non-admin must scope to a specific group they manage. raise Error::Forbidden.new("group_id is required") unless group_id @@ -70,7 +78,7 @@ module PlaceOS::Api .order(created_at: :desc, id: :desc) end - paginate_sql(query, type: "group_history", limit: limit, offset: offset) + paginate_sql(scope_history(query), type: "group_history", limit: limit, offset: offset) end @[AC::Route::GET("/:id")] diff --git a/src/placeos-rest-api/controllers/groups/invitation.cr b/src/placeos-rest-api/controllers/groups/invitation.cr index bb970bb7..1a9f97dd 100644 --- a/src/placeos-rest-api/controllers/groups/invitation.cr +++ b/src/placeos-rest-api/controllers/groups/invitation.cr @@ -25,6 +25,9 @@ module PlaceOS::Api def find_current_invitation(id : UUID) Log.context.set(invitation_id: id.to_s) @current_invitation = ::PlaceOS::Model::GroupInvitation.find!(id) + if Utils::Tenancy.enforce? + authority_for_resource!(::PlaceOS::Model::Group.find!(current_invitation.group_id).authority_id, "group") + end end getter! current_invitation : ::PlaceOS::Model::GroupInvitation @@ -77,7 +80,7 @@ module PlaceOS::Api limit : Int32 = 100, offset : Int32 = 0, ) : Array(::PlaceOS::Model::GroupInvitation) - authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + authority_id = resource_authority!.id.as(String) authority_group_ids = ::PlaceOS::Model::Group .where(authority_id: authority_id) .to_a @@ -87,6 +90,7 @@ module PlaceOS::Api query = ::PlaceOS::Model::GroupInvitation.where(group_id: authority_group_ids) if group_id + ensure_resource_authority!(::PlaceOS::Model::Group.find!(group_id).authority_id, "group") unless user_admin? group = ::PlaceOS::Model::Group.find!(group_id) ensure_manage!(current_user, group) @@ -114,6 +118,7 @@ module PlaceOS::Api @[AC::Route::POST("/", body: :payload, status_code: HTTP::Status::CREATED)] def create(payload : InvitationCreatePayload) : InvitationCreatedResponse group = ::PlaceOS::Model::Group.find!(UUID.new(payload.group_id)) + authority_for_resource!(group.authority_id, "group") if Utils::Tenancy.enforce? ensure_manage!(current_user, group) unless user_admin? perms = ::PlaceOS::Model::Permissions.new(payload.permissions) diff --git a/src/placeos-rest-api/controllers/groups/user.cr b/src/placeos-rest-api/controllers/groups/user.cr index 95b485e1..536061b3 100644 --- a/src/placeos-rest-api/controllers/groups/user.cr +++ b/src/placeos-rest-api/controllers/groups/user.cr @@ -35,6 +35,7 @@ module PlaceOS::Api def find_current_group_user(user_id : String, group_id : UUID) Log.context.set(user_id: user_id, group_id: group_id.to_s) @current_group_user = ::PlaceOS::Model::GroupUser.find!({user_id, group_id}) + check_group_user_scope(current_group_user) end getter! current_group_user : ::PlaceOS::Model::GroupUser @@ -45,6 +46,13 @@ module PlaceOS::Api getter! group_user_update : ::PlaceOS::Model::GroupUser + private def check_group_user_scope(row : ::PlaceOS::Model::GroupUser) + return unless Utils::Tenancy.enforce? + group = ::PlaceOS::Model::Group.find!(row.group_id) + authority_for_resource!(group.authority_id, "group") + ensure_resource_authority!(::PlaceOS::Model::User.find!(row.user_id).authority_id, "user") + end + # Permission gates ############################################################################################### @@ -60,6 +68,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:create])] def check_create_permissions + check_group_user_scope(group_user_update) return if user_admin? group = ::PlaceOS::Model::Group.find!(group_user_update.group_id) ensure_manage!(current_user, group) @@ -85,7 +94,7 @@ module PlaceOS::Api offset : Int32 = 0, ) : Array(::PlaceOS::Model::GroupUser) # Constrain to the caller's authority. - authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + authority_id = resource_authority!.id.as(String) authority_group_ids = ::PlaceOS::Model::Group .where(authority_id: authority_id) .to_a @@ -97,12 +106,16 @@ module PlaceOS::Api if user_id == "me" query = query.where(user_id: current_user.id.as(String)) elsif user_id + if Utils::Tenancy.enforce? + ensure_resource_authority!(::PlaceOS::Model::User.find!(user_id).authority_id, "user") + end # Only sys_admin can look up other users. raise Error::Forbidden.new unless user_admin? || user_id == current_user.id query = query.where(user_id: user_id) end if group_id + ensure_resource_authority!(::PlaceOS::Model::Group.find!(group_id).authority_id, "group") unless user_admin? group = ::PlaceOS::Model::Group.find!(group_id) # Non-Manager: allow only if asking about their own entries. diff --git a/src/placeos-rest-api/controllers/groups/zone.cr b/src/placeos-rest-api/controllers/groups/zone.cr index 09e5046c..95160afa 100644 --- a/src/placeos-rest-api/controllers/groups/zone.cr +++ b/src/placeos-rest-api/controllers/groups/zone.cr @@ -32,6 +32,7 @@ module PlaceOS::Api def find_current_group_zone(group_id : UUID, zone_id : String) Log.context.set(group_id: group_id.to_s, zone_id: zone_id) @current_group_zone = ::PlaceOS::Model::GroupZone.find!({group_id, zone_id}) + check_group_zone_scope(current_group_zone) end getter! current_group_zone : ::PlaceOS::Model::GroupZone @@ -42,6 +43,13 @@ module PlaceOS::Api getter! group_zone_update : ::PlaceOS::Model::GroupZone + private def check_group_zone_scope(row : ::PlaceOS::Model::GroupZone) + return unless Utils::Tenancy.enforce? + group = ::PlaceOS::Model::Group.find!(row.group_id) + authority_for_resource!(group.authority_id, "group") + ensure_reach!(::PlaceOS::Model::Zone.find!(row.zone_id)) + end + # Permission gates ############################################################################################### @@ -54,6 +62,7 @@ module PlaceOS::Api @[AC::Route::Filter(:before_action, only: [:create])] def check_create_permissions + check_group_zone_scope(group_zone_update) return if user_admin? group = ::PlaceOS::Model::Group.find!(group_zone_update.group_id) ensure_manage!(current_user, group) @@ -79,7 +88,7 @@ module PlaceOS::Api limit : Int32 = 100, offset : Int32 = 0, ) : Array(::PlaceOS::Model::GroupZone) - authority_id = current_authority.as(::PlaceOS::Model::Authority).id.as(String) + authority_id = resource_authority!.id.as(String) authority_group_ids = ::PlaceOS::Model::Group .where(authority_id: authority_id) .to_a @@ -89,6 +98,7 @@ module PlaceOS::Api query = ::PlaceOS::Model::GroupZone.where(group_id: authority_group_ids) if group_id + ensure_resource_authority!(::PlaceOS::Model::Group.find!(group_id).authority_id, "group") unless user_admin? group = ::PlaceOS::Model::Group.find!(group_id) ensure_member!(current_user, group) @@ -102,7 +112,10 @@ module PlaceOS::Api end end - query = query.where(zone_id: zone_id) if zone_id + if zone_id + ensure_reach!(::PlaceOS::Model::Zone.find!(zone_id)) if Utils::Tenancy.enforce? + query = query.where(zone_id: zone_id) + end results = paginate_sql(query, type: "group_zones", limit: limit, offset: offset) hydrate_index(results) results diff --git a/src/placeos-rest-api/controllers/history.cr b/src/placeos-rest-api/controllers/history.cr index 94771a62..e4bca25f 100644 --- a/src/placeos-rest-api/controllers/history.cr +++ b/src/placeos-rest-api/controllers/history.cr @@ -14,8 +14,6 @@ module PlaceOS::Api before_action :can_write, only: [:undelete] before_action :check_admin - # history spans every organisation's records - before_action :check_cluster_admin ############################################################################################### @@ -31,10 +29,103 @@ module PlaceOS::Api {% end %} end + # Trusted snapshots bypass controller parsers, so restoring them must + # validate references and delegated credential rights explicitly. + private def ensure_restore_snapshot!(entry : ::PlaceOS::Model::History) + fields = entry.snapshot.try(&.as_h?) || raise Error::NotFound.new("deleted snapshot not found") + type = entry.resource_type + if type.in?({"partners", "organisations", "driver", "repository"}) + check_cluster_admin + end + if authority = fields["authority_id"]?.try(&.as_s?) + ensure_authority_reach!(authority, "authority", required: ::PlaceOS::Model::Permissions::Read) + if type.in?({"user", "api_key", "ldap_strat", "adfs_strat", "oauth_strat", "groups"}) + ensure_credential_management!(authority) + end + end + if owner = fields["owner_id"]?.try(&.as_s?) + ensure_authority_reach!(owner, "owner", required: ::PlaceOS::Model::Permissions::Read) + ensure_credential_management!(owner) + end + if type == "grants" + scope_type = fields["scope_type"]?.try(&.as_s?) + scope_id = fields["scope_id"]?.try(&.as_s?) + case scope_type + when "organisation" + ensure_reach!(scope_id.try { |id| UUID.parse?(id) }, "grant scope", required: ::PlaceOS::Model::Permissions::Manage) + when "authority" + ensure_credential_management!(scope_id) + else + check_cluster_admin + end + end + if parent = fields["parent_id"]?.try(&.as_s?).try(&.presence) + case type + when "zone" then ensure_reach!(::PlaceOS::Model::Zone.find!(parent), required: ::PlaceOS::Model::Permissions::Read) + when "groups" then ensure_authority_reach!(::PlaceOS::Model::Group.find!(UUID.new(parent)).authority_id, "group", required: ::PlaceOS::Model::Permissions::Read) + when "asset" then ensure_authority_reach!(::PlaceOS::Model::Asset.find!(parent).asset_type.try(&.category).try(&.authority_id), "asset", required: ::PlaceOS::Model::Permissions::Read) + end + end + {"zones", "modules"}.each do |name| + fields[name]?.try(&.as_a?).try &.each do |value| + if name == "zones" + ensure_reach!(::PlaceOS::Model::Zone.find!(value.as_s), required: ::PlaceOS::Model::Permissions::Read) + else + ensure_reach!(::PlaceOS::Model::Module.find!(value.as_s), required: ::PlaceOS::Model::Permissions::Read) + end + end + end + if id = fields["control_system_id"]?.try(&.as_s?).try(&.presence) + ensure_reach!(::PlaceOS::Model::ControlSystem.find!(id), required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["zone_id"]?.try(&.as_s?).try(&.presence) + ensure_reach!(::PlaceOS::Model::Zone.find!(id), required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["trigger_id"]?.try(&.as_s?).try(&.presence) + trigger = ::PlaceOS::Model::Trigger.find!(id) + ensure_reach!(trigger, required: ::PlaceOS::Model::Permissions::Read) if trigger.control_system_id + end + if id = fields["group_id"]?.try(&.as_s?) + authority = ::PlaceOS::Model::Group.find!(UUID.new(id)).authority_id + ensure_authority_reach!(authority, "group", required: ::PlaceOS::Model::Permissions::Read) + ensure_credential_management!(authority) + end + if id = fields["playlist_id"]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::Playlist.find!(id).authority_id, "playlist", required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["category_id"]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::AssetCategory.find!(id).authority_id, "category", required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["asset_type_id"]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::AssetType.find!(id).category.try(&.authority_id), "asset type", required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["purchase_order_id"]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::AssetPurchaseOrder.find!(id).authority_id, "purchase order", required: ::PlaceOS::Model::Permissions::Read) + end + if id = fields["alert_dashboard_id"]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::AlertDashboard.find!(id).authority_id, "dashboard", required: ::PlaceOS::Model::Permissions::Read) + end + {"item_id", "background_item_id"}.each do |name| + if id = fields[name]?.try(&.as_s?) + ensure_authority_reach!(::PlaceOS::Model::Playlist::Item.find!(id).authority_id, "media", required: ::PlaceOS::Model::Permissions::Read) + end + end + {"media_id", "thumbnail_id"}.each do |name| + if id = fields[name]?.try(&.as_s?) + ensure_upload_reach!(::PlaceOS::Model::Upload.find!(id), required: ::PlaceOS::Model::Permissions::Read) + end + end + if type.in?({"api_key", "edge", "group_users"}) && (id = fields["user_id"]?.try(&.as_s?)) + ensure_authority_reach!(::PlaceOS::Model::User.find!(id).authority_id, "user", required: ::PlaceOS::Model::Permissions::Read) + end + end + @[AC::Route::Filter(:before_action, only: [:show])] def find_current_history(id : UUID) Log.context.set(history_id: id.to_s) - @current_history = ::PlaceOS::Model::History.find!(id) + entry = ::PlaceOS::Model::History.find!(id) + ensure_history_reach!(entry) + @current_history = entry end getter! current_history : ::PlaceOS::Model::History @@ -65,7 +156,7 @@ module PlaceOS::Api @[AC::Param::Info(description: "the starting offset of the result set, used to implement pagination")] offset : Int32 = 0, ) : Array(::PlaceOS::Model::History) - query = ::PlaceOS::Model::History.order(created_at: :desc, id: :desc) + query = scope_history(::PlaceOS::Model::History.order(created_at: :desc, id: :desc)) query = query.where(resource_type: resource_types) if resource_types && !resource_types.empty? query = query.where_not(resource_type: exclude_resource_types) if exclude_resource_types && !exclude_resource_types.empty? query = query.where(resource_id: resource_id) if resource_id @@ -93,6 +184,12 @@ module PlaceOS::Api @[AC::Param::Info(description: "the id of the deleted resource", example: "zone-1234")] resource_id : String, ) : ::PgORM::Base + if Utils::Tenancy.enforce? && !platform_history? + entry = ::PlaceOS::Model::History.for_resource(resource_type, resource_id).where(action: "delete").first? + raise Error::NotFound.new("deleted record not found") unless entry + ensure_history_reach!(entry, ::PlaceOS::Model::Permissions::Create) + ensure_restore_snapshot!(entry) + end begin self.class.undelete(resource_type, resource_id) || raise Error::NotFound.new("#{resource_type} has no change history") rescue error : ::PgORM::Error::RecordNotFound diff --git a/src/placeos-rest-api/controllers/map_ai.cr b/src/placeos-rest-api/controllers/map_ai.cr index c7608775..73ae9c04 100644 --- a/src/placeos-rest-api/controllers/map_ai.cr +++ b/src/placeos-rest-api/controllers/map_ai.cr @@ -30,7 +30,7 @@ module PlaceOS::Api ############################################################################################### - getter authority : ::PlaceOS::Model::Authority { current_authority.as(::PlaceOS::Model::Authority) } + getter authority : ::PlaceOS::Model::Authority { resource_authority! } @[AC::Route::Filter(:before_action, only: [:show_job, :cancel, :resolve])] def find_current_job(id : UUID) @@ -456,6 +456,7 @@ module PlaceOS::Api private def markup_upload(upload_id : String) : ::PlaceOS::Model::Upload upload = ::PlaceOS::Model::Upload.find?(upload_id) raise Error::NotFound.new("no such upload") if upload.nil? + ensure_upload_reach!(upload, required: ::PlaceOS::Model::Permissions::Read) raise Error::ImageGen::Permission.new("that image is not yours") unless upload.uploaded_by == current_user.id if upload.file_size > SIGNAGE_AI_MAX_IMAGE_BYTES raise Error::ImageGen::Permission.new("that image is larger than #{SIGNAGE_AI_MAX_IMAGE_BYTES // (1024 * 1024)}MB") diff --git a/src/placeos-rest-api/controllers/metadata.cr b/src/placeos-rest-api/controllers/metadata.cr index ce486a7f..a6f57059 100644 --- a/src/placeos-rest-api/controllers/metadata.cr +++ b/src/placeos-rest-api/controllers/metadata.cr @@ -121,7 +121,7 @@ module PlaceOS::Api Log.context.set(zone_id: parent_id) current_zone = ::PlaceOS::Model::Zone.find!(parent_id) current_zone.children.all.compact_map do |zone| - Children.new(zone, name) if include_parent || zone.id != parent_id + Children.new(zone, name) if parent_in_reach?(zone.id.as(String)) && (include_parent || zone.id != parent_id) end end @@ -173,21 +173,21 @@ module PlaceOS::Api end payload = metadata.interface - spawn { self.class.signal_metadata(current_authority.not_nil!.id.to_s, :update, payload) } + publish_metadata_change(parent_id, :update, payload) payload end UNSCOPED_SIGNAL_CHANNEL = "placeos/metadata/changed" SCOPED_SIGNAL_CHANNEL = "placeos/%s/metadata/changed" - protected def self.signal_metadata(authority : String, action : Symbol, metadata) : Nil + protected def self.signal_metadata(authority : String, action : Symbol, metadata, scoped : Bool = Utils::Tenancy.enforce?) : Nil payload = { action: action, metadata: metadata, }.to_json Log.info { "signalling #{UNSCOPED_SIGNAL_CHANNEL} with #{payload.bytesize} bytes" } - ::PlaceOS::Driver::RedisStorage.with_redis &.publish(UNSCOPED_SIGNAL_CHANNEL, payload) + ::PlaceOS::Driver::RedisStorage.with_redis &.publish(UNSCOPED_SIGNAL_CHANNEL, payload) unless scoped unless Utils::Tenancy.enforce? signal_channel = sprintf(SCOPED_SIGNAL_CHANNEL, authority) Log.info { "signalling #{signal_channel} with #{payload.bytesize} bytes" } @@ -209,7 +209,7 @@ module PlaceOS::Api end payload = metadata.interface - spawn { self.class.signal_metadata(current_authority.not_nil!.id.to_s, :update, payload) } + publish_metadata_change(parent_id, :update, payload) payload end @@ -223,17 +223,10 @@ module PlaceOS::Api ) : Nil ::PlaceOS::Model::Metadata.for(parent_id, metadata_name).each &.destroy - spawn do - if metadata_name.empty? - self.class.signal_metadata(current_authority.not_nil!.id.to_s, :destroy_all, { - parent_id: parent_id, - }) - else - self.class.signal_metadata(current_authority.not_nil!.id.to_s, :destroy, { - parent_id: parent_id, - name: metadata_name, - }) - end + if metadata_name.empty? + publish_metadata_change(parent_id, :destroy_all, {parent_id: parent_id}) + else + publish_metadata_change(parent_id, :destroy, {parent_id: parent_id, name: metadata_name}) end end @@ -311,7 +304,7 @@ module PlaceOS::Api raise Error::Forbidden.new unless parent_id.starts_with? "zone-" # find the org zone - authority = current_authority.as(::PlaceOS::Model::Authority) + authority = resource_authority! org_zone_id = authority.config["org_zone"]?.try(&.as_s?) raise Error::Forbidden.new unless org_zone_id diff --git a/src/placeos-rest-api/controllers/modules.cr b/src/placeos-rest-api/controllers/modules.cr index 7c2b58ee..54a27605 100644 --- a/src/placeos-rest-api/controllers/modules.cr +++ b/src/placeos-rest-api/controllers/modules.cr @@ -94,7 +94,12 @@ module PlaceOS::Api # `GroupPermissions#module_debug_access?` @[AC::Route::Filter(:before_action, only: [:logs])] def check_debug_permissions - raise Error::Forbidden.new unless module_debug_access?(current_module.id.as(String)) + allowed = if Utils::Tenancy.enforce? + tenancy_policy.module_debug_access?(current_module.id.as(String)) + else + module_debug_access?(current_module.id.as(String)) + end + raise Error::Forbidden.new unless allowed end @[AC::Route::Filter(:before_action, only: [:settings])] @@ -191,6 +196,7 @@ module PlaceOS::Api ensure_reach!(cs) # Include subset of association data with results results = ::PlaceOS::Model::Module.find_all(cs.modules).compact_map do |mod| + next unless in_reach?(mod.organisation_id) next if (driver = mod.driver).nil? # Most human readable module data is contained in driver @@ -282,8 +288,8 @@ module PlaceOS::Api control_system_ids = search_results.compact_map(&.control_system_id).uniq! drivers = Model::Driver.find_all search_results.map(&.driver_id.as(String)).uniq! - control_systems = Model::ControlSystem.find_all(control_system_ids).to_a - zones = Model::Zone.find_all(control_systems.flat_map(&.zones)).to_a + control_systems = scope_organisations(Model::ControlSystem.where(id: control_system_ids), required: ::PlaceOS::Model::Permissions::Read).to_a + zones = scope_organisations(Model::Zone.where(id: control_systems.flat_map(&.zones)), required: ::PlaceOS::Model::Permissions::Read).to_a search_results.compact_map do |d| sys_id = d.control_system_id @@ -369,6 +375,10 @@ module PlaceOS::Api current = current_module can_modify?(current) current.assign_attributes(mod) + if Utils::Tenancy.enforce? && (system_id = current.control_system_id.presence) + system = ::PlaceOS::Model::ControlSystem.find!(system_id) + ensure_reach!(system) + end can_modify?(current) raise Error::ModelValidation.new(current.errors) unless current.save @@ -491,7 +501,7 @@ module PlaceOS::Api ) { |module_id| ::PlaceOS::Model::Module.find!(module_id).edge_id.as(String) }.exec( - security: driver_clearance(user_token), + security: Utils::Tenancy.enforce? ? tenancy_policy.resource_security(current_module.organisation_id) : driver_clearance(user_token), function: method, args: args, request_id: request_id, @@ -519,7 +529,7 @@ module PlaceOS::Api end # Dumps the complete status state of the module, key values are serialised JSON - @[AC::MCP(resource: "placeos://modules/{id}/state", mime_type: "application/json", cache_ttl: 0)] + @[AC::MCP(resource: "placeos://modules/{id}/state{?organisation_id}", mime_type: "application/json", cache_ttl: 0)] @[AC::Route::GET("/:id/state")] def state : Hash(String, String) self.class.module_state(current_module) @@ -527,7 +537,7 @@ module PlaceOS::Api # Returns the value of the requested status variable as JSON, `null` when it isn't set. # Subscribe to the resource to be notified when the value changes - @[AC::MCP(resource: "placeos://modules/{id}/state/{key}", mime_type: "application/json", subscribe: true, cache_ttl: 0)] + @[AC::MCP(resource: "placeos://modules/{id}/state/{key}{?organisation_id}", mime_type: "application/json", subscribe: true, cache_ttl: 0)] @[AC::Route::GET("/:id/state/:key/value")] def state_value( @[AC::Param::Info(description: "the name of the status variable", example: "power")] @@ -553,7 +563,7 @@ module PlaceOS::Api # `