diff --git a/OPENAPI_DOC.yml b/OPENAPI_DOC.yml index e44686b9..a3d8788a 100644 --- a/OPENAPI_DOC.yml +++ b/OPENAPI_DOC.yml @@ -19987,6 +19987,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" timezone: anyOf: - type: object @@ -20368,6 +20373,11 @@ components: - type: array items: type: string + organisation_id: + anyOf: + - type: string + format: uuid + - type: "null" place_id: anyOf: - type: "null" diff --git a/README.md b/README.md index 2bc06324..9ee92bd3 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,24 @@ LOGSTASH_HOST=example.com LOGSTASH_PORT=12345 ``` +### Domain isolation + +Staff API uses the authenticated request domain for its calendar context, including +email-domain tenant variants and delegated credentials. + +Configure the authority's `config.org_zone` to bound spaces and zones to that tree. +Without it, the API uses ownership only when the organisation has exactly one +PlaceOS domain and every owned room's zone references belong to that organisation. +Missing or ambiguous ownership returns HTTP 501 with an `org_zone` configuration +message. Unowned rooms and zones are excluded from the ownership fallback. + +`PLACE_TENANCY_ENFORCE=true` enables tenant-administration isolation after domain +organisation ownership has been assigned. It defaults to false during rollout. +Authority grants cover one domain; organisation and partner grants cover their +respective domains. Each request requires the matching grant operation or Manage, +alongside its existing JWT scope and admin requirements. Management partner staff +organisations retain cluster administration; customer organisations do not. + ## MCP Server The API is also available to LLM clients (Claude Code, Claude Desktop, VS Code, diff --git a/shard.lock b/shard.lock index 9359b121..266f4ab0 100644 --- a/shard.lock +++ b/shard.lock @@ -149,9 +149,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.5 + version: 9.123.5+git.commit.716ca764f68e09a72b9028aa3380fdb06a50a635 pool: git: https://github.com/ysbaddaden/pool.git diff --git a/shard.override.yml b/shard.override.yml index 32fab093..3f271f35 100644 --- a/shard.override.yml +++ b/shard.override.yml @@ -1,5 +1,10 @@ # NOTE:: here because of a shards ambiguous sources error dependencies: + # PPT-526: build against the multi-tenancy data layer until models #332 merges + placeos-models: + github: placeos/models + branch: PPT-526-partner-client + http-params-serializable: github: place-labs/http-params-serializable branch: chore/0.36.0 diff --git a/spec/controllers/calendars_spec.cr b/spec/controllers/calendars_spec.cr index 4a17d4dd..b3194c04 100644 --- a/spec/controllers/calendars_spec.cr +++ b/spec/controllers/calendars_spec.cr @@ -92,7 +92,7 @@ describe Calendars do WebMock.stub(:post, "https://graph.microsoft.com/v1.0/users/dev%40acaprojects.onmicrosoft.com/calendar/getSchedule") .to_return(body: File.read("./spec/fixtures/events/o365/get_schedule.json")) WebMock.stub(:post, "https://login.microsoftonline.com/bb89674a-238b-4b7d-91ec-6bebad83553a/oauth2/v2.0/token") - .to_return(body: "") + .to_return(body: File.read("./spec/fixtures/tokens/o365_token.json")) # this should return only two events tz = Time::Location.load("America/Los_Angeles") @@ -100,7 +100,9 @@ describe Calendars do later = Time.parse("2019-03-15T12:15:00", "%Y-%m-%dT%H:%M:%S", tz).to_unix route = "#{CALENDARS_BASE}/free_busy?calendars=dev@acaprojects.com&period_start=#{now}&period_end=#{later}&zone_ids=zone-EzcsmWbvUG6" - body = JSON.parse(client.get(route, headers: headers).body).as_a + response = client.get(route, headers: headers) + response.status_code.should eq 200 + body = JSON.parse(response.body).as_a body.should eq(CalendarsHelper.free_busy_output_15min) end @@ -111,14 +113,15 @@ describe Calendars do WebMock.stub(:post, "https://graph.microsoft.com/v1.0/users/dev%40acaprojects.onmicrosoft.com/calendar/getSchedule") .to_return(body: File.read("./spec/fixtures/events/o365/get_schedule.json")) WebMock.stub(:post, "https://login.microsoftonline.com/bb89674a-238b-4b7d-91ec-6bebad83553a/oauth2/v2.0/token") - .to_return(body: "") + .to_return(body: File.read("./spec/fixtures/tokens/o365_token.json")) tz = Time::Location.load("America/Los_Angeles") now = Time.parse("2019-03-15T12:00:00", "%Y-%m-%dT%H:%M:%S", tz).to_unix later = Time.parse("2019-03-15T12:04:00", "%Y-%m-%dT%H:%M:%S", tz).to_unix route = "#{CALENDARS_BASE}/free_busy?calendars=dev@acaprojects.com&period_start=#{now}&period_end=#{later}&zone_ids=zone-EzcsmWbvUG6" - bad_request = client.get(route, headers: headers).status_code - bad_request.should eq(400) + response = client.get(route, headers: headers) + response.status_code.should eq(400) + response.body.should contain("period_end") end describe "#check_permission" do diff --git a/spec/controllers/domain_isolation_regression_spec.cr b/spec/controllers/domain_isolation_regression_spec.cr new file mode 100644 index 00000000..3d9feae9 --- /dev/null +++ b/spec/controllers/domain_isolation_regression_spec.cr @@ -0,0 +1,164 @@ +require "./helpers/tenant_reach_helper" + +module StaffDomainRegressionSpec + alias Model = PlaceOS::Model + + def self.zone(org : Model::Organisation?) + Model::Generator.zone.tap(&.organisation_id = org.try(&.id)).save! + end + + def self.system(org : Model::Organisation?, zone : Model::Zone, feature : String) + Model::Generator.control_system.tap do |system| + system.organisation_id = org.try(&.id) + system.zones = [zone.id.as(String)] + system.bookable = true + system.features = Set{feature} + end.save! + end + + def self.type_body(category : Model::AssetCategory) + {name: "domain-type-#{UUID.random}", brand: "Regression", category_id: category.id}.to_json + end + + def self.clean_categories(categories : Array(Model::AssetCategory)) + Model::AssetType.where(category_id: categories.map(&.id)).each(&.delete) + categories.each(&.delete) + end +end + +describe "domain isolation regressions" do + client = AC::SpecHelper.client + + it "falls back to owned rooms and zones only for a single-authority organisation" do + TenantReachSpec.with_estate do |estate| + other_org = estate.new_organisation + estate.authority(other_org) + local_zone = StaffDomainRegressionSpec.zone(estate.organisation) + foreign_zone = StaffDomainRegressionSpec.zone(other_org) + unowned_zone = StaffDomainRegressionSpec.zone(nil) + local = StaffDomainRegressionSpec.system(estate.organisation, local_zone, "local-feature") + foreign = StaffDomainRegressionSpec.system(other_org, foreign_zone, "foreign-feature") + unowned = StaffDomainRegressionSpec.system(nil, unowned_zone, "unowned-feature") + begin + response = client.get(Spaces.base_route, headers: estate.headers) + response.status_code.should eq 200 + JSON.parse(response.body).as_a.map(&.["id"].as_s).should eq [local.id] + response.headers["X-Total-Count"].should eq "1" + response = client.get("#{Spaces.base_route}/zones", headers: estate.headers) + response.status_code.should eq 200 + JSON.parse(response.body).as_a.map(&.["id"].as_s).should eq [local_zone.id] + JSON.parse(client.get("#{Spaces.base_route}/features", headers: estate.headers).body).as_a.map(&.as_s).should eq ["local-feature"] + client.get("#{Spaces.base_route}/#{foreign.id}", headers: estate.headers).status_code.should eq 404 + client.get("#{Spaces.base_route}/#{local.id}", headers: estate.headers).status_code.should eq 200 + ensure + [local, foreign, unowned].each(&.delete) + [local_zone, foreign_zone, unowned_zone].each(&.delete) + end + end + end + + it "requires org_zone when a domain has no organisation ownership" do + TenantReachSpec.with_estate do |estate| + estate.authority.organisation_id = nil + estate.authority.save! + response = client.get(Spaces.base_route, headers: estate.headers) + response.status_code.should eq 501 + response.body.should contain("org_zone") + end + end + + it "requires org_zone instead of guessing between domains sharing an organisation" do + TenantReachSpec.with_estate do |estate| + estate.authority(estate.organisation) + response = client.get("#{Spaces.base_route}/zones", headers: estate.headers) + response.status_code.should eq 501 + response.body.should contain("org_zone") + end + end + + it "requires org_zone when an owned room references a foreign zone" do + TenantReachSpec.with_estate do |estate| + foreign_zone = StaffDomainRegressionSpec.zone(estate.new_organisation) + mixed = StaffDomainRegressionSpec.system(estate.organisation, foreign_zone, "mixed-estate") + begin + response = client.get(Spaces.base_route, headers: estate.headers) + response.status_code.should eq 501 + response.body.should contain("org_zone") + ensure + mixed.delete + foreign_zone.delete + end + end + end + + it "preserves explicit org_zone scoping for an existing unowned estate" do + TenantReachSpec.with_estate do |estate| + zone = StaffDomainRegressionSpec.zone(nil) + system = StaffDomainRegressionSpec.system(nil, zone, "configured-estate") + begin + estate.authority.organisation_id = nil + estate.authority.config_will_change! + estate.authority.config["org_zone"] = JSON::Any.new(zone.id.as(String)) + estate.authority.save! + response = client.get(Spaces.base_route, headers: estate.headers) + response.status_code.should eq 200 + JSON.parse(response.body).as_a.map(&.["id"].as_s).should eq [system.id] + response = client.get("#{Spaces.base_route}/zones", headers: estate.headers) + JSON.parse(response.body).as_a.map(&.["id"].as_s).should eq [zone.id] + ensure + system.delete + zone.delete + end + end + end + + it "rejects asset type creation in a foreign category" do + TenantReachSpec.with_estate do |estate| + foreign = estate.authority(estate.new_organisation) + category = PlaceOS::Model::Generator.asset_category(foreign).save! + begin + response = client.post(AssetTypes.base_route, headers: estate.headers, body: StaffDomainRegressionSpec.type_body(category)) + response.status_code.should eq 403 + PlaceOS::Model::AssetType.where(category_id: category.id).count.should eq 0 + ensure + StaffDomainRegressionSpec.clean_categories([category]) + end + end + end + + it "rejects moving an owned asset type to a foreign category" do + TenantReachSpec.with_estate do |estate| + foreign = estate.authority(estate.new_organisation) + own_category = PlaceOS::Model::Generator.asset_category(estate.authority).save! + foreign_category = PlaceOS::Model::Generator.asset_category(foreign).save! + type = PlaceOS::Model::Generator.asset_type(own_category).save! + begin + response = client.patch("#{AssetTypes.base_route}/#{type.id}", headers: estate.headers, body: {category_id: foreign_category.id}.to_json) + response.status_code.should eq 403 + PlaceOS::Model::AssetType.find!(type.id).category_id.should eq own_category.id + ensure + StaffDomainRegressionSpec.clean_categories([own_category, foreign_category]) + end + end + end + + it "preserves asset type changes within the domain and legacy unowned categories" do + TenantReachSpec.with_estate do |estate| + first = PlaceOS::Model::Generator.asset_category(estate.authority).save! + second = PlaceOS::Model::Generator.asset_category(estate.authority).save! + legacy = PlaceOS::Model::Generator.asset_category(estate.authority).save! + # Legacy NULLs are supported by the database, but new model writes require an authority. + PgORM::Database.connection(&.exec("UPDATE asset_category SET authority_id = NULL WHERE id = $1", legacy.id)) + type = PlaceOS::Model::Generator.asset_type(first).save! + begin + client.post(AssetTypes.base_route, headers: estate.headers, body: StaffDomainRegressionSpec.type_body(second)).status_code.should eq 201 + response = client.patch("#{AssetTypes.base_route}/#{type.id}", headers: estate.headers, body: {category_id: second.id}.to_json) + response.status_code.should eq 200 + PlaceOS::Model::AssetType.find!(type.id).category_id.should eq second.id + client.post(AssetTypes.base_route, headers: estate.headers, body: StaffDomainRegressionSpec.type_body(legacy)).status_code.should eq 201 + ensure + StaffDomainRegressionSpec.clean_categories([first, second, legacy]) + end + end + end +end diff --git a/spec/controllers/helpers/tenant_reach_helper.cr b/spec/controllers/helpers/tenant_reach_helper.cr new file mode 100644 index 00000000..bd968208 --- /dev/null +++ b/spec/controllers/helpers/tenant_reach_helper.cr @@ -0,0 +1,82 @@ +require "../../spec_helper" + +module TenantReachSpec + alias Model = PlaceOS::Model + alias Permissions = Model::Permissions + + class Estate + getter partner : Model::Partner + getter organisation : Model::Organisation + getter authority : Model::Authority + getter user : Model::User + getter own_tenant : Tenant + @organisations = [] of Model::Organisation + @authorities = [] of Model::Authority + @grants = [] of Model::Grant + + def initialize(management = false, staff = false, admin = true) + @partner = Model::Generator.partner(management: management).save! + @organisation = new_organisation(@partner, staff) + @authority = authority(@organisation) + @user = Model::Generator.user(@authority, admin: admin).save! + @own_tenant = Model::Generator.tenant(domain: @authority.domain) + end + + def new_organisation(partner : Model::Partner? = nil, staff = false) : Model::Organisation + org = Model::Generator.organisation(partner: partner, partner_staff: staff).save! + @organisations << org + org + end + + def authority(org : Model::Organisation) : Model::Authority + domain = "reach-#{UUID.random}.example.com" + authority = Model::Generator.authority(domain).tap(&.organisation_id = org.id).save! + @authorities << authority + authority + end + + def tenant(authority : Model::Authority) : Tenant + Model::Generator.tenant(domain: authority.domain) + end + + def grant(scope : String, id : String, permissions : Permissions, expires_at : Time? = nil) : Model::Grant + grant = Model::Generator.grant(@user, scope, id, permissions, expires_at).save! + @grants << grant + grant + end + + def headers(scope = [UserJWT::Scope::PUBLIC]) : HTTP::Headers + generated = Model::Generator.jwt(@user, scope) + token = UserJWT.new( + iss: generated.iss, iat: generated.iat, exp: generated.exp, + domain: @authority.domain, id: generated.id, user: generated.user, scope: generated.scope, + ) + HTTP::Headers{"Host" => @authority.domain, "Authorization" => "Bearer #{token.encode}", "Content-Type" => "application/json"} + end + + def close + @grants.each(&.delete) + Tenant.where(domain: @authorities.map(&.domain)).each(&.delete) + @user.delete + @authorities.reverse_each(&.delete) + @organisations.reverse_each(&.delete) + @partner.delete + end + end + + def self.with_estate(management = false, staff = false, admin = true, &) + estate = Estate.new(management, staff, admin) + Utils::Tenancy.enforce = true + begin + yield estate + ensure + Utils::Tenancy.enforce = false + estate.close + end + end + + def self.body(domain : String, email_domain : String? = nil) + {name: "Reach regression", domain: domain, email_domain: email_domain, platform: "office365", + credentials: {tenant: "t", client_id: "c", client_secret: "s"}}.to_json + end +end diff --git a/spec/controllers/tenant_reach_regression_spec.cr b/spec/controllers/tenant_reach_regression_spec.cr new file mode 100644 index 00000000..4dc3cc87 --- /dev/null +++ b/spec/controllers/tenant_reach_regression_spec.cr @@ -0,0 +1,128 @@ +require "./helpers/tenant_reach_helper" + +describe "tenant administration reach regressions" do + client = AC::SpecHelper.client + + it "keeps management-partner customer admins inside their own organisation" do + TenantReachSpec.with_estate(management: true) do |estate| + foreign = estate.tenant(estate.authority(estate.new_organisation)) + rows = JSON.parse(client.get(Tenants.base_route, headers: estate.headers).body).as_a + rows.map(&.["domain"].as_s).should eq [estate.authority.domain] + client.delete("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers).status_code.should eq 404 + Tenant.find?(foreign.id).should_not be_nil + end + end + + it "retains management staff cluster reach and ordinary partner staff reach" do + TenantReachSpec.with_estate(management: true, staff: true) do |estate| + foreign = estate.tenant(estate.authority(estate.new_organisation)) + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 200 + end + TenantReachSpec.with_estate(staff: true) do |estate| + managed = estate.tenant(estate.authority(estate.new_organisation(estate.partner))) + foreign = estate.tenant(estate.authority(estate.new_organisation)) + client.get("#{Tenants.base_route}/#{managed.id}/limits", headers: estate.headers).status_code.should eq 200 + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 404 + end + end + + it "keeps authority grants inside the exact domain, including list results" do + TenantReachSpec.with_estate do |estate| + other_org = estate.new_organisation + allowed = estate.authority(other_org) + sibling = estate.tenant(estate.authority(other_org)) + allowed_tenant = estate.tenant(allowed) + estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, allowed.id.to_s, TenantReachSpec::Permissions::Read) + domains = JSON.parse(client.get(Tenants.base_route, headers: estate.headers).body).as_a.map(&.["domain"].as_s) + domains.sort.should eq [estate.authority.domain, allowed.domain].sort + client.get("#{Tenants.base_route}/#{allowed_tenant.id}/limits", headers: estate.headers).status_code.should eq 200 + client.get("#{Tenants.base_route}/#{sibling.id}/limits", headers: estate.headers).status_code.should eq 404 + end + end + + it "does not turn a read grant into tenant update, create or delete access" do + TenantReachSpec.with_estate do |estate| + foreign_authority = estate.authority(estate.new_organisation) + foreign = estate.tenant(foreign_authority) + estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, foreign_authority.id.to_s, TenantReachSpec::Permissions::Read) + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 200 + client.patch("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers, body: {early_checkin: 17}.to_json).status_code.should eq 404 + Tenant.find(foreign.id).early_checkin.should_not eq 17 + client.post(Tenants.base_route, headers: estate.headers, body: TenantReachSpec.body(foreign_authority.domain, "new.example.com")).status_code.should eq 404 + client.delete("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers).status_code.should eq 404 + Tenant.find?(foreign.id).should_not be_nil + end + end + + it "honours operation-only grants without widening the other verbs" do + TenantReachSpec.with_estate do |estate| + foreign_authority = estate.authority(estate.new_organisation) + foreign = estate.tenant(foreign_authority) + grant = estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, foreign_authority.id.to_s, TenantReachSpec::Permissions::Update) + client.patch("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers, body: {early_checkin: 19}.to_json).status_code.should eq 200 + Tenant.find(foreign.id).early_checkin.should eq 19 + client.post("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers, body: {desk: 7}.to_json).status_code.should eq 200 + client.post("#{Tenants.base_route}/#{foreign.id}/early_checkin", headers: estate.headers, body: "21").status_code.should eq 200 + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 404 + client.delete("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers).status_code.should eq 404 + + grant.permission_flags = TenantReachSpec::Permissions::Create + grant.save! + response = client.post(Tenants.base_route, headers: estate.headers, body: TenantReachSpec.body(foreign_authority.domain, "created.example.com")) + response.status_code.should eq 201 + client.patch("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers, body: {early_checkin: 23}.to_json).status_code.should eq 404 + + grant.permission_flags = TenantReachSpec::Permissions::Delete + grant.save! + client.delete("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers).status_code.should eq 202 + Tenant.find?(foreign.id).should be_nil + end + end + + it "intersects grants with JWT scope and the existing admin role" do + TenantReachSpec.with_estate do |estate| + foreign_authority = estate.authority(estate.new_organisation) + foreign = estate.tenant(foreign_authority) + estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, foreign_authority.id.to_s, TenantReachSpec::Permissions::Manage) + read_headers = estate.headers([UserJWT::Scope.new("public", :read)]) + client.patch("#{Tenants.base_route}/#{foreign.id}", headers: read_headers, body: {early_checkin: 23}.to_json).status_code.should eq 403 + Tenant.find(foreign.id).early_checkin.should_not eq 23 + end + TenantReachSpec.with_estate(admin: false) do |estate| + foreign_authority = estate.authority(estate.new_organisation) + foreign = estate.tenant(foreign_authority) + estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, foreign_authority.id.to_s, TenantReachSpec::Permissions::Manage) + client.patch("#{Tenants.base_route}/#{foreign.id}", headers: estate.headers, body: {early_checkin: 23}.to_json).status_code.should eq 403 + end + end + + it "rejects a destination outside reach before changing a tenant's domain" do + TenantReachSpec.with_estate do |estate| + foreign_authority = estate.authority(estate.new_organisation) + estate.tenant(foreign_authority) + response = client.patch("#{Tenants.base_route}/#{estate.own_tenant.id}", headers: estate.headers, + body: TenantReachSpec.body(foreign_authority.domain, "redirected.example.com")) + response.status_code.should eq 404 + Tenant.find(estate.own_tenant.id).domain.should eq estate.authority.domain + client.patch("#{Tenants.base_route}/#{estate.own_tenant.id}", headers: estate.headers, body: {early_checkin: 29}.to_json).status_code.should eq 200 + client.get("#{Tenants.base_route}/current_early_checkin", headers: estate.headers).body.should eq "29" + end + end + + it "ignores expired and revoked grants without changing host validation" do + TenantReachSpec.with_estate do |estate| + foreign_authority = estate.authority(estate.new_organisation) + foreign = estate.tenant(foreign_authority) + grant = estate.grant(PlaceOS::Model::Grant::SCOPE_AUTHORITY, foreign_authority.id.to_s, TenantReachSpec::Permissions::Manage, 1.minute.ago) + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 404 + grant.expires_at = nil + grant.save! + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 200 + grant.delete + client.get("#{Tenants.base_route}/#{foreign.id}/limits", headers: estate.headers).status_code.should eq 404 + headers = estate.headers + headers["Host"] = foreign_authority.domain + client.get("#{Tenants.base_route}/current_limits", headers: headers).status_code.should eq 401 + end + end +end diff --git a/spec/controllers/tenants_scope_spec.cr b/spec/controllers/tenants_scope_spec.cr new file mode 100644 index 00000000..89e01966 --- /dev/null +++ b/spec/controllers/tenants_scope_spec.cr @@ -0,0 +1,61 @@ +require "../spec_helper" + +# PPT-526: tenant administration stays inside the caller's organisations +describe Tenants do + client = AC::SpecHelper.client + headers = Mock::Headers.office365_guest + + after_each { Utils::Tenancy.enforce = false } + + it "scopes tenant administration to the caller's reach" do + Utils::Tenancy.enforce = true + toby = PlaceOS::Model::Authority.find_by_domain("toby.staff-api.dev").not_nil! + + management = PlaceOS::Model::Generator.partner(management: true).save! + staff = PlaceOS::Model::Generator.organisation(partner: management, partner_staff: true).save! + stranger_org = PlaceOS::Model::Generator.organisation.save! + stranger = PlaceOS::Model::Generator.authority("stranger.staff-api.dev").tap(&.organisation_id = stranger_org.id).save! + stranger_tenant = PlaceOS::Model::Generator.tenant(name: "Stranger", domain: "stranger.staff-api.dev") + + begin + # a domain with no organisation reaches nothing + toby.organisation_id = nil + toby.save! + JSON.parse(client.get(Tenants.base_route, headers: headers).body).as_a.should be_empty + client.get("#{Tenants.base_route}/#{stranger_tenant.id}/limits", headers: headers).status_code.should eq 404 + + # the management partner's staff reach every tenant + toby.organisation_id = staff.id + toby.save! + domains = JSON.parse(client.get(Tenants.base_route, headers: headers).body).as_a.map(&.["domain"].as_s) + domains.should contain("toby.staff-api.dev") + domains.should contain("stranger.staff-api.dev") + client.get("#{Tenants.base_route}/#{stranger_tenant.id}/limits", headers: headers).status_code.should eq 200 + + # an ordinary organisation's admin sees only its own tenants + own_org = PlaceOS::Model::Generator.organisation.save! + toby.organisation_id = own_org.id + toby.save! + domains = JSON.parse(client.get(Tenants.base_route, headers: headers).body).as_a.map(&.["domain"].as_s) + domains.should eq ["toby.staff-api.dev"] + client.get("#{Tenants.base_route}/#{stranger_tenant.id}/limits", headers: headers).status_code.should eq 404 + client.patch("#{Tenants.base_route}/#{stranger_tenant.id}", headers: headers, body: {early_checkin: 60}.to_json).status_code.should eq 404 + + body = {name: "Sneaky", domain: "stranger.staff-api.dev", platform: "office365", credentials: {tenant: "t", client_id: "c", client_secret: "s"}}.to_json + client.post(Tenants.base_route, headers: headers, body: body).status_code.should eq 404 + + # a grant into the stranger's organisation widens reach + admin = PlaceOS::Model::User.find!(UserJWT.decode(Mock::Token.office).id) + PlaceOS::Model::Generator.grant(admin, PlaceOS::Model::Grant::SCOPE_ORGANISATION, stranger_org.id.to_s).save! + client.get("#{Tenants.base_route}/#{stranger_tenant.id}/limits", headers: headers).status_code.should eq 200 + ensure + toby.organisation_id = nil + toby.save! + stranger_tenant.delete + stranger.destroy + PlaceOS::Model::Grant.clear + PlaceOS::Model::Organisation.clear + PlaceOS::Model::Partner.clear + end + end +end diff --git a/spec/migration/Dockerfile b/spec/migration/Dockerfile index 57ff5e26..99447e77 100644 --- a/spec/migration/Dockerfile +++ b/spec/migration/Dockerfile @@ -4,7 +4,8 @@ WORKDIR /app COPY . /app -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/src/constants.cr b/src/constants.cr index 255b3144..c43ba6b8 100644 --- a/src/constants.cr +++ b/src/constants.cr @@ -7,8 +7,11 @@ module App {% end %} ENVIRONMENT = ENV["SG_ENV"]? || "development" - TEST = ENVIRONMENT == "test" - PRODUCTION = ENVIRONMENT == "production" + + # PPT-526: refuse cross-organisation tenant administration (true) or only log it (false) + PLACE_TENANCY_ENFORCE = ENV["PLACE_TENANCY_ENFORCE"]?.try(&.downcase).in?("true", "1", "yes") || false + TEST = ENVIRONMENT == "test" + PRODUCTION = ENVIRONMENT == "production" BUILD_TIME = {{ system("date -u").stringify }} BUILD_COMMIT = {{ env("PLACE_COMMIT") || "DEV" }} diff --git a/src/controllers/application.cr b/src/controllers/application.cr index bea7d5d0..ca7b87da 100644 --- a/src/controllers/application.cr +++ b/src/controllers/application.cr @@ -11,6 +11,7 @@ abstract class Application < ActionController::Base # ========================================= include Utils::PlaceOSHelpers include Utils::CurrentUser + include Utils::Tenancy include Utils::MultiTenant # the number of requests to queue before responding with too many requests @@ -106,13 +107,11 @@ abstract class Application < ActionController::Base protected def check_jwt_scope access = user_token.get_access("public") - block_access = true - - if request.method.downcase == "get" - block_access = access.none? - else - block_access = !access.write? - end + block_access = if request.method.downcase == "get" + access.none? + else + !access.write? + end if block_access Log.warn { {message: "unknown scope #{user_token.scope}", action: "authorize!", host: request.hostname, id: user_token.id} } diff --git a/src/controllers/asset_types.cr b/src/controllers/asset_types.cr index da0fee74..a11a6134 100644 --- a/src/controllers/asset_types.cr +++ b/src/controllers/asset_types.cr @@ -52,6 +52,14 @@ class AssetTypes < Application raise Error::NotFound.new("asset type #{current_asset_type.id} not found") end + private def confirm_category_authority(asset_type : ::PlaceOS::Model::AssetType) : Nil + # Resolve the current id directly: a cached association can predate assignment. + category = asset_type.category_id.try { |id| ::PlaceOS::Model::AssetCategory.find?(id) } + owner = category.try(&.authority_id) + return if owner.nil? || owner == current_authority.as(::PlaceOS::Model::Authority).id + raise Error::Forbidden.new("asset category belongs to another authority") + end + ############################################################################################### # List asset types, each with a count of its assets. @@ -139,7 +147,7 @@ class AssetTypes < Application GROUP BY at.id, at.name, at.brand, at.description, at.model_number, at.images, at.category_id, at.created_at, at.updated_at ) subquery; - SQL + SQL result = PgORM::Database.connection do |db| db.query_one sql, args: args, &.read(JSON::PullParser?).try &.read_raw @@ -160,6 +168,7 @@ class AssetTypes < Application def update(asset_type : ::PlaceOS::Model::AssetType) : ::PlaceOS::Model::AssetType current = current_asset_type current.assign_attributes(asset_type) + confirm_category_authority(current) raise Error::ModelValidation.new(current.errors) unless current.save current end @@ -167,6 +176,7 @@ class AssetTypes < Application # 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 + confirm_category_authority(asset_type) raise Error::ModelValidation.new(asset_type.errors) unless asset_type.save asset_type end diff --git a/src/controllers/spaces.cr b/src/controllers/spaces.cr index cd5f9e49..8e881004 100644 --- a/src/controllers/spaces.cr +++ b/src/controllers/spaces.cr @@ -142,7 +142,30 @@ class Spaces < Application current_authority.try(&.config["org_zone"]?.try(&.as_s?)) end - # the zones in the organisation's tree, every zone when there's no org zone + @fallback_organisation_id : UUID? = nil + + # Ownership is a domain boundary only when the organisation has exactly one domain. + private def fallback_organisation_id : UUID + @fallback_organisation_id ||= begin + org_id = current_authority.try(&.organisation_id) + message = "configure org_zone for this domain: its room estate cannot be determined safely" + unless org_id && ::PlaceOS::Model::Authority.where(organisation_id: org_id).count == 1 + raise Error::NotImplemented.new(message) + end + + invalid_references = ::PlaceOS::Model::ControlSystem.where(organisation_id: org_id, bookable: true).where(<<-SQL, org_id).exists? + EXISTS ( + SELECT 1 FROM unnest(sys.zones) AS referenced(id) + LEFT JOIN zone AS owned_zone ON owned_zone.id = referenced.id + WHERE owned_zone.organisation_id IS DISTINCT FROM ?::uuid + ) + SQL + raise Error::NotImplemented.new(message) if invalid_references + org_id + end + end + + # Zones in the configured tree, or in the verified single-domain estate. private def org_zones zones = ::PlaceOS::Model::Zone.all if org = org_zone_id @@ -156,16 +179,30 @@ class Spaces < Application SELECT id FROM tree ) SQL + else + zones = zones.where(organisation_id: fallback_organisation_id) end zones end + private def zones_for_space(ids : Array(String)) : Array(::PlaceOS::Model::Zone) + return [] of ::PlaceOS::Model::Zone if ids.empty? + zones = ::PlaceOS::Model::Zone.where(id: ids) + zones = zones.where(organisation_id: fallback_organisation_id) unless org_zone_id + zones.to_a + end + # SQL limiting systems to bookable ones in every zone listed and the org zone private def space_scope(zone_ids : Array(String)? = nil) : Tuple(String, Array(::PgORM::Value)) clauses = ["bookable = true"] args = [] of ::PgORM::Value zones = zone_ids.try(&.dup) || [] of String - org_zone_id.try { |org| zones << org } + if org = org_zone_id + zones << org + else + clauses << "organisation_id = ?" + args << fallback_organisation_id + end zones.uniq! unless zones.empty? clauses << "zones @> #{sql_array(zones)}" @@ -282,7 +319,7 @@ class Spaces < Application ) : SpaceSchedule system = current_space zone_ids = system.zones - zones = zone_ids.empty? ? [] of ::PlaceOS::Model::Zone : ::PlaceOS::Model::Zone.find_all(zone_ids).to_a + zones = zones_for_space(zone_ids) # the most specific zone with a timezone, systems list their zones from org down to level location = system.timezone || zone_ids.reverse.compact_map { |zone_id| zones.find(&.id.==(zone_id)).try(&.timezone) }.first? || @@ -341,7 +378,7 @@ class Spaces < Application @[AC::Route::GET("/:id/map")] def map : Nil system = current_space - zones = system.zones.empty? ? [] of ::PlaceOS::Model::Zone : ::PlaceOS::Model::Zone.find_all(system.zones).to_a.select!(&.map_id.presence) + zones = zones_for_space(system.zones).select!(&.map_id.presence) # the space's level, otherwise its most specific zone with a map (systems list zones from the org down) level = zones.find(&.tags.includes?("level")) || system.zones.reverse.compact_map { |zone_id| zones.find(&.id.==(zone_id)) }.first? diff --git a/src/controllers/tenants.cr b/src/controllers/tenants.cr index f8fcd0cd..804930e6 100644 --- a/src/controllers/tenants.cr +++ b/src/controllers/tenants.cr @@ -13,7 +13,14 @@ class Tenants < Application @[AC::Route::Filter(:before_action, except: [:index, :create, :current_limits, :current_early_checkin])] private def find_tenant(id : Int64) - @tenant = Tenant.find(id) + found = Tenant.find(id) + required = case request.method + when "GET", "HEAD" then ::PlaceOS::Model::Permissions::Read + when "DELETE" then ::PlaceOS::Model::Permissions::Delete + else ::PlaceOS::Model::Permissions::Update + end + ensure_domain_reach!(found.domain, required: required) + @tenant = found end getter! tenant : Tenant @@ -25,13 +32,16 @@ class Tenants < Application # List the tenants. @[AC::Route::GET("/")] def index : Array(Tenant::Responder) - Tenant.select(:id, :name, :domain, :email_domain, :platform, :booking_limits, :booking_range, :booking_period, :delegated, :service_account, :outlook_config, :early_checkin).to_a.map(&.as_json) + tenants = Tenant.select(:id, :name, :domain, :email_domain, :platform, :booking_limits, :booking_range, :booking_period, :delegated, :service_account, :outlook_config, :early_checkin).to_a + scope_tenants(tenants).map(&.as_json) end # Create a tenant. @[AC::Route::POST("/", body: :tenant_body, status_code: HTTP::Status::CREATED)] def create(tenant_body : Tenant::Responder) : Tenant::Responder tenant = tenant_body.to_tenant + tenant.domain = tenant.domain.strip.downcase + ensure_domain_reach!(tenant.domain, "domain", required: ::PlaceOS::Model::Permissions::Create) tenant.save! rescue raise Error::ModelValidation.new(tenant.errors.map { |error| {field: error.field.to_s, reason: error.message}.as({field: String?, reason: String}) }, "error validating tenant data") tenant.as_json end @@ -41,6 +51,9 @@ class Tenants < Application @[AC::Route::PATCH("/:id", body: :tenant_body)] def update(tenant_body : Tenant::Responder) : Tenant::Responder changes = tenant_body.to_tenant(update: true) + if domain = tenant_body.domain + ensure_domain_reach!(domain.strip.downcase, "domain", required: ::PlaceOS::Model::Permissions::Update) + end {% for key in [:name, :domain, :email_domain, :platform, :delegated, :booking_limits, :service_account, :credentials, :outlook_config, :early_checkin] %} begin diff --git a/src/controllers/utilities/tenancy.cr b/src/controllers/utilities/tenancy.cr new file mode 100644 index 00000000..b43cabeb --- /dev/null +++ b/src/controllers/utilities/tenancy.cr @@ -0,0 +1,106 @@ +require "placeos-models" + +# Organisation reach for tenant administration (PPT-526). Mirrors the +# rest-api resolver: cluster reach for the management partner's staff, +# partner reach for a partner's staff organisation, otherwise the caller's +# own organisation, widened by live grants. Tenants are addressed by domain, +# so reach is expressed as the hostnames of the domains in reach. +module Utils::Tenancy + Log = ::App::Log.for("tenancy") + alias TenancyPermissions = ::PlaceOS::Model::Permissions + + class_property? enforce : Bool = App::PLACE_TENANCY_ENFORCE + + record Scope, cluster : Bool, domain_permissions : Hash(String, TenancyPermissions) + + getter tenancy_scope : Scope { resolve_tenancy_scope } + + protected def resolve_tenancy_scope : Scope + permissions = Hash(String, TenancyPermissions).new(TenancyPermissions::None) + authority = ::PlaceOS::Model::Authority.find_by_domain(request.hostname.as(String)) + organisation = authority.try(&.organisation) + if organisation.nil? + Log.warn { {message: "domain has no organisation, caller reaches nothing", host: request.hostname, user_id: user_token.id} } + return Scope.new(false, permissions) + end + + partner = organisation.partner_id.try { |id| ::PlaceOS::Model::Partner.find?(id) } + privileged = is_support? + return Scope.new(true, permissions) if privileged && partner && partner.management && organisation.partner_staff + + ids = if privileged && partner && organisation.partner_staff + organisation.partner_organisations.to_a.compact_map(&.id).to_set + else + Set{organisation.id.as(UUID)} + end + + add_organisation_permissions(permissions, ids.to_a, TenancyPermissions::Manage) + + unless user_token.guest_scope? + ::PlaceOS::Model::Grant.for_user(user_token.id).each do |grant| + flags = grant.permission_flags + case grant.scope_type + when ::PlaceOS::Model::Grant::SCOPE_ORGANISATION + UUID.parse?(grant.scope_id).try { |id| add_organisation_permissions(permissions, [id], flags) } + when ::PlaceOS::Model::Grant::SCOPE_PARTNER + if partner_id = UUID.parse?(grant.scope_id) + org_ids = ::PlaceOS::Model::Organisation.where(partner_id: partner_id).to_a.compact_map(&.id) + add_organisation_permissions(permissions, org_ids, flags) + end + when ::PlaceOS::Model::Grant::SCOPE_AUTHORITY + if target = ::PlaceOS::Model::Authority.find?(grant.scope_id) + permissions[target.domain] |= flags + end + end + end + end + + Scope.new(false, permissions) + end + + private def add_organisation_permissions(permissions : Hash(String, TenancyPermissions), ids : Array(UUID), flags : TenancyPermissions) : Nil + return if ids.empty? + list = ids.map(&.to_s) + ::PlaceOS::Model::Authority + .where("organisation_id = ANY(ARRAY[#{list.join(", ") { "?" }}]::uuid[])", list) + .each { |authority| permissions[authority.domain] |= flags } + end + + # Hostnames allowed for this operation; nil for cluster reach + def reachable_domains(required : TenancyPermissions = TenancyPermissions::Read) : Array(String)? + scope = tenancy_scope + return if scope.cluster + scope.domain_permissions.select { |_, flags| flags.manage? || flags.includes?(required) }.keys + end + + def domain_in_reach?(domain : String, required : TenancyPermissions = TenancyPermissions::Read) : Bool + scope = tenancy_scope + return true if scope.cluster + flags = scope.domain_permissions[domain] + flags.manage? || flags.includes?(required) + end + + # 404 for a tenant on a domain outside reach, so foreign ids look unknown + def ensure_domain_reach!(domain : String, resource : String = "tenant", required : TenancyPermissions = TenancyPermissions::Read) : Nil + return if domain_in_reach?(domain, required) + Log.warn do + { + message: Utils::Tenancy.enforce? ? "tenancy refused" : "tenancy would refuse", + resource: resource, + domain: domain, + required: required.to_s, + user_id: user_token.id, + path: request.path, + } + end + raise Error::NotFound.new("#{resource} not found") if Utils::Tenancy.enforce? + end + + # Keeps only the tenants whose domain is in reach; unchanged when not enforcing + def scope_tenants(tenants : Array(Tenant)) : Array(Tenant) + return tenants unless Utils::Tenancy.enforce? + domains = reachable_domains + return tenants if domains.nil? + tenants.select { |tenant| domains.includes?(tenant.domain) } + end +end