diff --git a/CHANGELOG.md b/CHANGELOG.md index 005273a2..02aa6cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Add explicit `@gql.authorize.byAncestor({reason})` dispositions with static + path-dominance validation, audit-manifest provenance, and no repeated runtime + policy evaluation. + ## 1.3.0 - Add opt-in required authorization coverage with typed `.authorize` policies, explicit `.public` dispositions, resolver outcomes, mutation prechecks, interface policy inheritance, custom forbidden handlers, and deterministic audit manifests. diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index 9d105c10..9bb7c31d 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -85,7 +85,62 @@ A policy must have: Type, interface, field, and resolver policies compose additively. Interface field public dispositions and interface resolver outcomes also propagate to concrete implementations. Policies execute in declaration order with AND semantics and stop at the first `Forbidden`. Converted field arguments are constructed once and shared by every policy and the resolver. Async code is generated only when a policy or outcome is promise-backed. -A policy on a field returning an object does not authorize that object's child fields. Each output field needs its own disposition. +By default, a policy on a field returning an object does not authorize that +object's child fields. Each output field needs its own disposition. + +### Authorization by an ancestor + +Connection wrappers, mutation payloads, and calculated result objects often +have no authorization identity independent of the field that produced them. +After reviewing that relationship, mark their fields as authorized by an +ancestor: + +```rescript +@gql.authorize.byAncestor({ + reason: "Connection fields expose only the authorized campaign result", +}) +@gql.type +type campaignConnection = { + @gql.field + edges: array, +} + +@gql.authorize(CampaignSecurity.canList) +@gql.field +let campaigns = async ( + _: query, + ~organizationId: string, + ~ctx: ResGraphContext.context, +): campaignConnection => { + await ctx.dataLoaders.campaigns.load(~organizationId) +} +``` + +On a concrete object type, `@gql.authorize.byAncestor` is a default for each +immediate GraphQL field, including separately declared resolver fields. It is +not recursively copied to returned object types: `campaignEdge` must declare +its own disposition. The annotation can also be placed directly on one field. +A direct field policy, public declaration, or resolver outcome overrides a type +default. A field-level `byAncestor` annotation cannot be combined with one of +those direct dispositions. + +ResGraph statically proves that every root-to-field path crosses an ordinary +`@gql.authorize(...)` policy or an allowed resolver outcome before the annotated +field. A public field is not an authorization boundary. If the same object type +is reachable through an unprotected path, generation fails at the +`byAncestor` annotation. Lists and nullability are transparent to the proof; +unions and interface return types fan out to their concrete object types. +`byAncestor` is currently supported on concrete object types and fields, not +on interfaces or subscription paths. Paths from subscription roots are treated +as unprotected even when the subscription field declares a policy, because +ResGraph cannot yet enforce that policy for each delivered event. Shared return +types therefore cannot hide an unsafe subscription path. + +The annotation generates no runtime check. Upstream policies run only where +they are declared, so expensive authorization is not reevaluated for structural +child fields. Mutation root fields still require a pre-resolver policy before a +payload type may use `byAncestor`; a mutation's post-resolver outcome does not +serve as that ancestor boundary. ## Resolver outcomes @@ -137,7 +192,7 @@ let onForbidden = ( ## Audit manifest and boundaries -`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, public reason, source locations, resolver-outcome metadata, and mutation status. Commit it when authorization posture should be reviewed through diffs. +`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, public or `byAncestor` review reason, source locations, resolver-outcome metadata, and mutation status. For an `authorizedByAncestor` field, `ancestorBoundaries` lists the nearest possible policy or resolver-outcome boundaries across its protected paths. Only policies declared on the selected runtime path execute. Commit the manifest when authorization posture should be reviewed through diffs. Fields on inferred union payload objects use the `synthetic` disposition. They have no annotation surface and are reachable only after their parent resolver diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index 696de9a1..519be527 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -267,7 +267,7 @@ let validateFunction ~loader ~(package : SharedTypes.package) ~schemaState let declaration schemaState coordinate = match Hashtbl.find_opt schemaState.authorizationDeclarations coordinate with | Some declaration -> declaration - | None -> {functions = []; public = None} + | None -> {functions = []; public = None; byAncestor = None} type plannedReference = { reference: authorizationFunctionReference; @@ -319,6 +319,31 @@ let interfacePublic schemaState (typ : gqlObjectType) fieldName = ~parentTypeName:intf.displayName ~fieldName)) .public) +let addUnsupportedInterfaceAncestorDiagnostics (schemaState : schemaState) = + let check coordinate = + match (declaration schemaState coordinate).byAncestor with + | None -> () + | Some byAncestor -> + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + "`@gql.authorize.byAncestor` is currently supported on \ + concrete object types and their fields, not interfaces."; + } + in + schemaState.interfaces + |> GenerateSchemaUtils.iterHashtblAlphabetically + (fun _ (intf : gqlInterface) -> + check intf.displayName; + intf.fields + |> List.iter (fun field -> + check + (GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:intf.displayName ~fieldName:field.name))) module BaselineEntry = struct type t = string * authorizationGapKind @@ -394,7 +419,7 @@ let loadBaseline path = BaselineEntries.empty let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public - ~references ~resolverOutcome = + ~references ~byAncestor ~resolverOutcome = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -402,7 +427,8 @@ let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public if typ.id = "subscription" then Some (coordinate, UnsupportedSubscription) else if synthetic then None else if - Option.is_none public && references = [] && Option.is_none resolverOutcome + Option.is_none public && references = [] && Option.is_none byAncestor + && Option.is_none resolverOutcome then Some (coordinate, UncoveredField) else if typ.id = "mutation" && Option.is_none public && references = [] then Some (coordinate, MutationPreResolverPolicy) @@ -434,8 +460,7 @@ let addGapDiagnostic schemaState ~(field : gqlField) (coordinate, kind) = ~diagnostic:{loc = field.loc; fileUri = field.fileUri; message} let buildFieldPlan ~loader ~package ~(schemaState : schemaState) - ~baselineEntries ~skipGapDiagnostics ~(typ : gqlObjectType) - ~(field : gqlField) = + ~(typ : gqlObjectType) ~(field : gqlField) = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -494,8 +519,247 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) coordinate; } | _ -> ()); + let hasDirectDisposition = + hasPolicies || Option.is_some public || Option.is_some resolverOutcome + in + let byAncestor = + match fieldDeclaration.byAncestor with + | Some byAncestor when hasDirectDisposition -> + let conflictAlreadyDiagnosed = + fieldDeclaration.functions <> [] + || Option.is_some fieldDeclaration.public + in + if not conflictAlreadyDiagnosed then + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + Printf.sprintf + "`%s` is authorized by an ancestor but also has a direct \ + authorization disposition. Field-level direct policies, \ + public declarations, and resolver outcomes cannot be \ + combined with `@gql.authorize.byAncestor`." + coordinate; + }; + None + | Some byAncestor -> Some byAncestor + | None when hasDirectDisposition -> None + | None -> typeDeclaration.byAncestor + in + Hashtbl.replace schemaState.authorizationPlans coordinate + { + functions; + byAncestor; + ancestorBoundaries = []; + public; + resolverOutcome; + synthetic; + baselineGap = None; + } + +module AncestorAuthorizationBoundary = struct + type t = ancestorAuthorizationBoundary + + let compare = Stdlib.compare +end + +module AncestorAuthorizationBoundaries = Set.Make (AncestorAuthorizationBoundary) + +type ancestorReachability = { + hasUnprotectedPath: bool; + boundaries: AncestorAuthorizationBoundaries.t; +} + +let rec outputTypeIds ~processedSchema = function + | List inner | Nullable inner | RescriptNullable inner -> + outputTypeIds ~processedSchema inner + | GraphQLObjectType {id} -> [id] + | GraphQLUnion _ -> [] + | GraphQLInterface {id} -> ( + match Hashtbl.find_opt processedSchema.interfaceImplementedBy id with + | None -> [] + | Some implementations -> + implementations + |> List.filter_map (fun (implementation : interfaceImplementedBy) -> + match implementation with + | ObjectType typ -> Some typ.id + | Interface _ -> None)) + | Scalar _ | EmptyPayload | InjectContext | InjectInfo + | InjectInterfaceTypename _ | GraphQLInputObject _ | GraphQLInputUnion _ + | GraphQLEnum _ | GraphQLScalar _ -> + [] + +let unionMemberIds (schemaState : schemaState) = function + | GraphQLUnion {id} -> ( + match Hashtbl.find_opt schemaState.unions id with + | None -> [] + | Some union -> + union.types + |> List.map (fun (member : gqlUnionMember) -> member.objectTypeId)) + | _ -> [] + +let fieldOutputTypeIds ~processedSchema (schemaState : schemaState) + (field : gqlField) = + let rec ids = function + | List inner | Nullable inner | RescriptNullable inner -> ids inner + | GraphQLUnion _ as union -> unionMemberIds schemaState union + | typ -> outputTypeIds ~processedSchema typ + in + ids field.typ |> List.sort_uniq String.compare + +let localPolicyBoundaries coordinate (plan : effectiveAuthorizationPlan) = + plan.functions + |> List.map (fun fn -> AncestorPolicy {boundaryCoordinate = coordinate; fn}) + |> AncestorAuthorizationBoundaries.of_list + +let localAuthorizationBoundaries coordinate (plan : effectiveAuthorizationPlan) + = + let boundaries = localPolicyBoundaries coordinate plan in + match plan.resolverOutcome with + | None -> boundaries + | Some outcome -> + boundaries + |> AncestorAuthorizationBoundaries.add + (AncestorResolverOutcome {boundaryCoordinate = coordinate; outcome}) + +let updateReachability reachability typeId incoming = + match Hashtbl.find_opt reachability typeId with + | None -> + Hashtbl.add reachability typeId incoming; + true + | Some existing -> + let merged = + { + hasUnprotectedPath = + existing.hasUnprotectedPath || incoming.hasUnprotectedPath; + boundaries = + AncestorAuthorizationBoundaries.union existing.boundaries + incoming.boundaries; + } + in + if + Bool.equal merged.hasUnprotectedPath existing.hasUnprotectedPath + && AncestorAuthorizationBoundaries.equal merged.boundaries + existing.boundaries + then false + else ( + Hashtbl.replace reachability typeId merged; + true) + +let ancestorReachability ~processedSchema (schemaState : schemaState) = + let reachability = Hashtbl.create 50 in + let pending = Queue.create () in + let enqueueRoot = function + | None -> () + | Some (typ : gqlObjectType) -> + if + updateReachability reachability typ.id + { + hasUnprotectedPath = true; + boundaries = AncestorAuthorizationBoundaries.empty; + } + then Queue.add typ.id pending + in + enqueueRoot schemaState.query; + enqueueRoot schemaState.mutation; + enqueueRoot schemaState.subscription; + while not (Queue.is_empty pending) do + let typeId = Queue.take pending in + match + ( Hashtbl.find_opt schemaState.types typeId, + Hashtbl.find_opt reachability typeId ) + with + | Some typ, Some incoming -> + typ.fields + |> List.iter (fun field -> + let coordinate = + GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:typ.displayName ~fieldName:field.name + in + let plan = Hashtbl.find schemaState.authorizationPlans coordinate in + let localBoundaries = + if typ.id = "subscription" then + AncestorAuthorizationBoundaries.empty + else if typ.id = "mutation" then + localPolicyBoundaries coordinate plan + else localAuthorizationBoundaries coordinate plan + in + let outgoing = + { + hasUnprotectedPath = + incoming.hasUnprotectedPath + && AncestorAuthorizationBoundaries.is_empty localBoundaries; + boundaries = + (if AncestorAuthorizationBoundaries.is_empty localBoundaries + then incoming.boundaries + else localBoundaries); + } + in + fieldOutputTypeIds ~processedSchema schemaState field + |> List.iter (fun outputTypeId -> + if updateReachability reachability outputTypeId outgoing then + Queue.add outputTypeId pending)) + | _ -> () + done; + reachability + +let applyAncestorAuthorization ~processedSchema (schemaState : schemaState) = + let reachability = ancestorReachability ~processedSchema schemaState in + schemaState.types + |> Hashtbl.iter (fun typeId (typ : gqlObjectType) -> + typ.fields + |> List.iter (fun field -> + let coordinate = + GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:typ.displayName ~fieldName:field.name + in + match Hashtbl.find_opt schemaState.authorizationPlans coordinate with + | None -> () + | Some {byAncestor = None} -> () + | Some ({byAncestor = Some byAncestor} as plan) -> ( + match Hashtbl.find_opt reachability typeId with + | Some {hasUnprotectedPath = false; boundaries} + when not (AncestorAuthorizationBoundaries.is_empty boundaries) -> + Hashtbl.replace schemaState.authorizationPlans coordinate + { + plan with + ancestorBoundaries = + AncestorAuthorizationBoundaries.elements boundaries; + } + | _ -> + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + Printf.sprintf + "Field `%s` uses `@gql.authorize.byAncestor`, but \ + ResGraph cannot prove that every path to it \ + crosses a preceding authorization policy or \ + resolver outcome." + coordinate; + }))) + +let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries + ~skipGapDiagnostics ~(typ : gqlObjectType) ~(field : gqlField) = + let coordinate = + GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName + ~fieldName:field.name + in + let plan = Hashtbl.find schemaState.authorizationPlans coordinate in + let references = + plan.functions + |> List.map (fun (fn : authorizationFunction) -> fn.reference) + in let gap = - gapForField ~typ ~field ~synthetic ~public ~references ~resolverOutcome + gapForField ~typ ~field ~synthetic:plan.synthetic ~public:plan.public + ~references ~byAncestor:plan.byAncestor + ~resolverOutcome:plan.resolverOutcome in let baselineGap = match (schemaState.authorizationConfig.mode, gap, baselineEntries) with @@ -506,7 +770,7 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) | _ -> None in Hashtbl.replace schemaState.authorizationPlans coordinate - {functions; public; resolverOutcome; synthetic; baselineGap}; + {plan with baselineGap}; (match gap with | Some entry -> schemaState.authorizationGaps <- entry :: schemaState.authorizationGaps @@ -537,7 +801,7 @@ let addStaleBaselineDiagnostics schemaState ~path ~baselineEntries = (authorizationGapKindToString kind); }) -let buildPlans ~loader ~package (schemaState : schemaState) = +let buildPlans ~loader ~package ~processedSchema (schemaState : schemaState) = let baselineEntries, baselineLoadFailed = match ( schemaState.authorizationConfig.mode, @@ -553,12 +817,20 @@ let buildPlans ~loader ~package (schemaState : schemaState) = (None, true)) | _ -> (None, false) in + addUnsupportedInterfaceAncestorDiagnostics schemaState; schemaState.types |> GenerateSchemaUtils.iterHashtblAlphabetically (fun _ (typ : gqlObjectType) -> typ.fields |> List.iter (fun field -> - buildFieldPlan ~loader ~package ~schemaState ~baselineEntries + buildFieldPlan ~loader ~package ~schemaState ~typ ~field)); + applyAncestorAuthorization ~processedSchema schemaState; + schemaState.types + |> GenerateSchemaUtils.iterHashtblAlphabetically + (fun _ (typ : gqlObjectType) -> + typ.fields + |> List.iter (fun field -> + finalizeFieldPlan ~schemaState ~baselineEntries ~skipGapDiagnostics:baselineLoadFailed ~typ ~field)); match (baselineEntries, schemaState.authorizationConfig.baselinePath) with | Some entries, Some path -> @@ -590,6 +862,17 @@ let manifestPolicy ~package (fn : authorizationFunction) = (jsonString (Loc.toString fn.reference.loc)) (if fn.isAsync then "true" else "false") +let manifestAncestorBoundary ~package = function + | AncestorPolicy {boundaryCoordinate; fn} -> + Printf.sprintf "{\"coordinate\":%s,\"kind\":\"policy\",\"policy\":%s}" + (jsonString boundaryCoordinate) + (manifestPolicy ~package fn) + | AncestorResolverOutcome {boundaryCoordinate; outcome = {isAsync}} -> + Printf.sprintf + "{\"coordinate\":%s,\"kind\":\"resolverOutcome\",\"resolverOutcome\":{\"async\":%s}}" + (jsonString boundaryCoordinate) + (if isAsync then "true" else "false") + let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = let disposition = match @@ -597,14 +880,16 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = plan.synthetic, plan.public, plan.functions, + plan.byAncestor, plan.resolverOutcome ) with - | Some _, _, _, _, _ -> "baseline" - | None, true, _, _, _ -> "synthetic" - | None, false, Some _, _, _ -> "public" - | None, false, None, _ :: _, _ -> "policies" - | None, false, None, [], Some _ -> "resolverOutcome" - | None, false, None, [], None -> "uncovered" + | Some _, _, _, _, _, _ -> "baseline" + | None, true, _, _, _, _ -> "synthetic" + | None, false, Some _, _, _, _ -> "public" + | None, false, None, _ :: _, _, _ -> "policies" + | None, false, None, [], _, Some _ -> "resolverOutcome" + | None, false, None, [], Some _, None -> "authorizedByAncestor" + | None, false, None, [], None, None -> "uncovered" in let publicJson = match plan.public with @@ -615,19 +900,37 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = (jsonString (relativeSourcePath ~package public.fileUri)) (jsonString (Loc.toString public.loc)) in + let byAncestorJson = + match plan.byAncestor with + | None -> "null" + | Some byAncestor -> + Printf.sprintf "{\"reason\":%s,\"file\":%s,\"location\":%s}" + (jsonString byAncestor.reason) + (jsonString (relativeSourcePath ~package byAncestor.fileUri)) + (jsonString (Loc.toString byAncestor.loc)) + in let resolverOutcomeJson = match plan.resolverOutcome with | None -> "null" | Some {isAsync} -> Printf.sprintf "{\"async\":%s}" (if isAsync then "true" else "false") in + let ancestorBoundariesJson = + match plan.ancestorBoundaries with + | [] -> "" + | boundaries -> + Printf.sprintf ",\"ancestorBoundaries\":[%s]" + (boundaries + |> List.map (manifestAncestorBoundary ~package) + |> String.concat ",") + in Printf.sprintf - "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"resolverOutcome\":%s}" + "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"byAncestor\":%s,\"resolverOutcome\":%s%s}" (jsonString coordinate) (jsonString disposition) (if String.starts_with coordinate ~prefix:"Mutation." then "true" else "false") (plan.functions |> List.map (manifestPolicy ~package) |> String.concat ",") - publicJson resolverOutcomeJson + publicJson byAncestorJson resolverOutcomeJson ancestorBoundariesJson let rec ensureDirectory path = if path = "" || path = "." || Sys.file_exists path then () @@ -639,7 +942,7 @@ let generatedManifest ~status ~fields = Printf.sprintf "{\n\ \ \"generatedBy\": \"resgraph\",\n\ - \ \"version\": 1,\n\ + \ \"version\": 2,\n\ \ \"status\": \"%s\",\n\ \ \"fields\": [\n\ \ %s\n\ @@ -655,8 +958,9 @@ let isGeneratedManifest path = | None -> false | Some json -> let status = Option.bind (Json.get "status" json) Json.string in + let version = Option.bind (Json.get "version" json) Json.number in Option.bind (Json.get "generatedBy" json) Json.string = Some "resgraph" - && Option.bind (Json.get "version" json) Json.number = Some 1. + && (version = Some 1. || version = Some 2.) && (status = Some "generationFailed" || status = Some "success") && Option.is_some (Option.bind (Json.get "fields" json) Json.array)) diff --git a/src/ml/GenerateSchemaDirect.ml b/src/ml/GenerateSchemaDirect.ml index 33ab94b8..1821b61a 100644 --- a/src/ml/GenerateSchemaDirect.ml +++ b/src/ml/GenerateSchemaDirect.ml @@ -234,7 +234,8 @@ let generateSchemaDirect ~printToStdOut ~writeStateFile ~sourceFolder ~debug let processedSchema = GenerateSchemaUtils.processSchema schemaState in - GenerateSchemaAuthorization.buildPlans ~loader ~package schemaState; + GenerateSchemaAuthorization.buildPlans ~loader ~package + ~processedSchema schemaState; let markNamedSchemaFile contents = match schemaName with | Some _ -> diff --git a/src/ml/GenerateSchemaTypePrinters.ml b/src/ml/GenerateSchemaTypePrinters.ml index 3c4baeed..19b3ed39 100644 --- a/src/ml/GenerateSchemaTypePrinters.ml +++ b/src/ml/GenerateSchemaTypePrinters.ml @@ -47,6 +47,8 @@ let printResolverForField ~parentTypeName ~(schemaState : schemaState) | None -> { functions = []; + byAncestor = None; + ancestorBoundaries = []; public = None; resolverOutcome = Hashtbl.find_opt schemaState.resolverOutcomes coordinate; diff --git a/src/ml/GenerateSchemaTypes.ml b/src/ml/GenerateSchemaTypes.ml index 4296555a..afbe0572 100644 --- a/src/ml/GenerateSchemaTypes.ml +++ b/src/ml/GenerateSchemaTypes.ml @@ -47,9 +47,12 @@ type authorizationFunctionReference = { type publicAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} +type ancestorAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} + type declaredAuthorization = { functions: authorizationFunctionReference list; public: publicAuthorization option; + byAncestor: ancestorAuthorization option; } type authorizationInjection = AuthorizationContext | AuthorizationInfo @@ -76,12 +79,21 @@ type authorizationGapKind = type effectiveAuthorizationPlan = { functions: authorizationFunction list; + byAncestor: ancestorAuthorization option; + ancestorBoundaries: ancestorAuthorizationBoundary list; public: publicAuthorization option; resolverOutcome: resolverOutcome option; synthetic: bool; baselineGap: authorizationGapKind option; } +and ancestorAuthorizationBoundary = + | AncestorPolicy of {boundaryCoordinate: string; fn: authorizationFunction} + | AncestorResolverOutcome of { + boundaryCoordinate: string; + outcome: resolverOutcome; + } + type typeLocationLoc = { fileName: string; fileUri: Uri.t; diff --git a/src/ml/GenerateSchemaUtils.ml b/src/ml/GenerateSchemaUtils.ml index dcdba004..79693cee 100644 --- a/src/ml/GenerateSchemaUtils.ml +++ b/src/ml/GenerateSchemaUtils.ml @@ -43,6 +43,8 @@ let validAttributes = ("gql.scalar", ""); ("gql.authorize", "Attaches a typed authorization function."); ("gql.public", "Marks a field public with a required reason."); + ( "gql.authorize.byAncestor", + "Marks a field as authorized by a policy on every path to it." ); ] let hasGqlAnnotation attributes = @@ -93,7 +95,10 @@ let extractGqlAttribute ~(schemaState : GenerateSchemaTypes.schemaState) | ["gql"; "union"] -> Some Union | ["gql"; "inputObject"] -> Some InputObject | ["gql"; "inputUnion"] -> Some InputUnion - | ["gql"; "authorize"] | ["gql"; "public"] -> None + | ["gql"; "authorize"] + | ["gql"; "authorize"; "byAncestor"] + | ["gql"; "public"] -> + None | "gql" :: _ -> schemaState |> addDiagnostic @@ -148,7 +153,7 @@ let extractGqlImplementsAttributes | _ -> None) let emptyDeclaredAuthorization : declaredAuthorization = - {functions = []; public = None} + {functions = []; public = None; byAncestor = None} let authorizationCoordinate ~parentTypeName ~fieldName = parentTypeName ^ "." ^ fieldName @@ -164,6 +169,15 @@ let addAuthorizationDiagnostic ~schemaState ~(env : SharedTypes.QueryEnv.t) ~loc let functionReferenceFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) = + let reference functionPath = + let path = Longident.flatten functionPath in + if List.length path < 2 then ( + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize` requires a module-qualified function path, for \ + example `Security.canRead`."; + None) + else Some {path; loc = attributeLoc; fileUri = env.file.uri} + in match payload with | PStr [ @@ -172,21 +186,16 @@ let functionReferenceFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) Pstr_eval ({pexp_desc = Pexp_ident {txt = functionPath}}, _); }; ] -> - let path = Longident.flatten functionPath in - if List.length path < 2 then ( - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` requires a module-qualified function path, for \ - example `Security.canRead`."; - None) - else Some {path; loc = attributeLoc; fileUri = env.file.uri} + reference functionPath | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for example \ `Security.canRead`."; None -let publicReasonFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) - ~attributeLoc (payload : Parsetree.payload) = +let reasonStringFromPayload ~annotation ~schemaState + ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) + = let reason = match payload with | PStr @@ -211,54 +220,91 @@ let publicReasonFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) 0 in match reason with - | Some reason when nonWhitespaceLength reason >= 3 -> - Some {reason; loc = attributeLoc; fileUri = env.file.uri} + | Some reason when nonWhitespaceLength reason >= 3 -> Some reason | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.public` requires a reason with at least 3 non-whitespace \ - characters, for example `@gql.public({reason: \"Public profile \ - data\"})`."; + (Printf.sprintf + "`%s` requires a reason with at least 3 non-whitespace characters, \ + for example `%s({reason: \"Reviewed authorization disposition\"})`." + annotation annotation); None let extractDeclaredAuthorization ~allowPublic ~schemaState ~(env : SharedTypes.QueryEnv.t) (attributes : Parsetree.attributes) = - attributes - |> List.fold_left - (fun (declared : declaredAuthorization) - ((name, payload) : Parsetree.attribute) -> - match String.split_on_char '.' name.txt with - | ["gql"; "authorize"] -> ( - match - functionReferenceFromPayload ~schemaState ~env - ~attributeLoc:name.loc payload - with - | None -> declared - | Some fn -> {declared with functions = declared.functions @ [fn]}) - | ["gql"; "public"] -> ( - if not allowPublic then ( - addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc - "`@gql.public` can only be used on output fields or resolver \ - functions, not on a type."; - declared) - else + let declared = + attributes + |> List.fold_left + (fun (declared : declaredAuthorization) + ((name, payload) : Parsetree.attribute) -> + match String.split_on_char '.' name.txt with + | ["gql"; "authorize"] -> ( match - publicReasonFromPayload ~schemaState ~env ~attributeLoc:name.loc - payload + functionReferenceFromPayload ~schemaState ~env + ~attributeLoc:name.loc payload with | None -> declared - | Some public -> ( - match declared.public with - | None -> {declared with public = Some public} + | Some fn -> {declared with functions = declared.functions @ [fn]}) + | ["gql"; "authorize"; "byAncestor"] -> ( + match + reasonStringFromPayload ~annotation:"@gql.authorize.byAncestor" + ~schemaState ~env ~attributeLoc:name.loc payload + with + | None -> declared + | Some reason -> ( + match declared.byAncestor with + | None -> + { + declared with + byAncestor = + Some {reason; loc = name.loc; fileUri = env.file.uri}; + } | Some _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc - "Only one `@gql.public` annotation is allowed per field."; + "Only one `@gql.authorize.byAncestor` annotation is allowed \ + per field or type."; declared)) - | _ -> declared) - emptyDeclaredAuthorization + | ["gql"; "public"] -> ( + if not allowPublic then ( + addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc + "`@gql.public` can only be used on output fields or resolver \ + functions, not on a type."; + declared) + else + match + reasonStringFromPayload ~annotation:"@gql.public" ~schemaState + ~env ~attributeLoc:name.loc payload + with + | None -> declared + | Some reason -> ( + match declared.public with + | None -> + { + declared with + public = + Some {reason; loc = name.loc; fileUri = env.file.uri}; + } + | Some _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc + "Only one `@gql.public` annotation is allowed per field."; + declared)) + | _ -> declared) + emptyDeclaredAuthorization + in + (match (declared.byAncestor, declared.functions, declared.public) with + | Some byAncestor, _ :: _, _ | Some byAncestor, _, Some _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:byAncestor.loc + "`@gql.authorize.byAncestor` cannot be combined with \ + `@gql.authorize(...)` or `@gql.public` on the same field or type." + | _ -> ()); + declared let registerAuthorizationDeclaration ~coordinate (declared : declaredAuthorization) ~(schemaState : schemaState) = - if declared.functions = [] && Option.is_none declared.public then () + if + declared.functions = [] + && Option.is_none declared.public + && Option.is_none declared.byAncestor + then () else match Hashtbl.find_opt schemaState.authorizationDeclarations coordinate with | None -> @@ -275,6 +321,10 @@ let registerAuthorizationDeclaration ~coordinate (match (existing.public, declared.public) with | Some public, _ -> Some public | None, public -> public); + byAncestor = + (match (existing.byAncestor, declared.byAncestor) with + | Some byAncestor, _ -> Some byAncestor + | None, byAncestor -> byAncestor); } let registerAuthorizationAttributes ~coordinate ~allowPublic ~attributes @@ -1311,7 +1361,7 @@ type persistedLegacySchemaState = { } let stateFileMagic = "RESGRAPH_STATE\000" -let stateFileVersion = 1 +let stateFileVersion = 2 let validStateName schemaName = Str.string_match (Str.regexp "^[A-Za-z0-9_-]+$") schemaName 0 diff --git a/tests/authorization/invalid/src/Mutation.res b/tests/authorization/invalid/src/Mutation.res index 920d3518..39f09afc 100644 --- a/tests/authorization/invalid/src/Mutation.res +++ b/tests/authorization/invalid/src/Mutation.res @@ -1,8 +1,14 @@ @gql.type type mutation +@gql.authorize.byAncestor({reason: "Mutation payloads require a pre-resolver policy"}) @gql.type +type outcomeOnlyPayload = { + @gql.field + value: string, +} + @gql.field let outcomeOnly = (_: mutation): ResGraph.Authorization.outcome< + outcomeOnlyPayload, string, - string, -> => ResGraph.Authorization.Allowed("too late") +> => ResGraph.Authorization.Allowed({value: "too late"}) diff --git a/tests/authorization/invalid/src/Query.res b/tests/authorization/invalid/src/Query.res index de55adcb..a55ee106 100644 --- a/tests/authorization/invalid/src/Query.res +++ b/tests/authorization/invalid/src/Query.res @@ -39,3 +39,37 @@ let badContext = (_: query): string => "bad context" @gql.authorize(Security.nonUnitOutcome) @gql.field let nonUnitOutcome = (_: query): string => "bad outcome" + +@gql.type +@gql.authorize.byAncestor({reason: "Shared selection fields rely on their protected entry path"}) +type sharedSelection = { + @gql.field + value: string, +} + +@gql.authorize(Security.canSelect) @gql.field +let protectedSelection = (_: query): sharedSelection => {value: "protected"} + +@gql.authorize(Security.canSelect) @gql.field +let protectedSubscriptionEvent = (_: query): SubscriptionEvent.subscriptionEvent => { + value: "protected", +} + +@gql.public({reason: "Intentionally exercises an unprotected alternate path"}) @gql.field +let publicSelection = (_: query): sharedSelection => {value: "public"} + +@gql.authorize.byAncestor({reason: "Root field incorrectly claims an ancestor policy"}) @gql.field +let noAncestor = (_: query): string => "no ancestor" + +@gql.authorize.byAncestor({reason: "Conflicts with a direct field policy"}) +@gql.authorize(Security.good) +@gql.field +let ancestorConflict = (_: query): string => "conflict" + +@gql.authorize.byAncestor({reason: "a b"}) @gql.field +let shortAncestorReason = (_: query): string => "short" + +@gql.authorize.byAncestor({reason: "First review"}) +@gql.authorize.byAncestor({reason: "Second review"}) +@gql.field +let duplicateAncestor = (_: query): string => "duplicate" diff --git a/tests/authorization/invalid/src/Security.res b/tests/authorization/invalid/src/Security.res index d997be59..a2b24051 100644 --- a/tests/authorization/invalid/src/Security.res +++ b/tests/authorization/invalid/src/Security.res @@ -53,3 +53,7 @@ let nonUnitOutcome = (_: Query.query, ~args: {.}): ResGraph.Authorization.outcom string, reason, > => ResGraph.Authorization.Allowed("wrong") + +let canSelect = (_: Query.query, ~args: {.}) => ResGraph.Authorization.Allowed() + +let canSubscribe = (_: Subscription.subscription, ~args: {.}) => ResGraph.Authorization.Allowed() diff --git a/tests/authorization/invalid/src/Subscription.res b/tests/authorization/invalid/src/Subscription.res index 31b93526..17c259e2 100644 --- a/tests/authorization/invalid/src/Subscription.res +++ b/tests/authorization/invalid/src/Subscription.res @@ -1,12 +1,15 @@ @gql.type type subscription -let makeAsyncIterator: (unit => promise>) => AsyncIterator.t< - string, -> = %raw(`function makeAsyncIterator(next) { +let makeAsyncIterator: ( + unit => promise> +) => AsyncIterator.t = %raw(`function makeAsyncIterator(next) { return {next, [Symbol.asyncIterator]() { return this }} }`) -@gql.public({reason: "Still rejected until subscription semantics are defined"}) @gql.field -let events = (_: subscription): AsyncIterator.t => - makeAsyncIterator(async () => {AsyncIterator.done: true, value: Some("event")}) +@gql.authorize(Security.canSubscribe) @gql.field +let events = (_: subscription): AsyncIterator.t => + makeAsyncIterator(async () => { + AsyncIterator.done: true, + value: Some({SubscriptionEvent.value: "event"}), + }) diff --git a/tests/authorization/invalid/src/SubscriptionEvent.res b/tests/authorization/invalid/src/SubscriptionEvent.res new file mode 100644 index 00000000..25ca3680 --- /dev/null +++ b/tests/authorization/invalid/src/SubscriptionEvent.res @@ -0,0 +1,6 @@ +@gql.type +type subscriptionEvent = { + @gql.authorize.byAncestor({reason: "Subscription events require per-event authorization"}) + @gql.field + value: string, +} diff --git a/tests/authorization/invalid/src/UnsupportedInterface.res b/tests/authorization/invalid/src/UnsupportedInterface.res new file mode 100644 index 00000000..5be72cf9 --- /dev/null +++ b/tests/authorization/invalid/src/UnsupportedInterface.res @@ -0,0 +1,11 @@ +@gql.authorize.byAncestor({reason: "Interface fields rely on an upstream policy"}) @gql.interface +type unsupportedAncestor = { + @gql.authorize.byAncestor({reason: "Interface field relies on an upstream policy"}) @gql.field + value: string, +} + +@gql.implements("UnsupportedAncestor") @gql.type +type unsupportedConcrete = { + @gql.field + value: string, +} diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index 9200f7d6..c0144c42 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -58,14 +58,50 @@ grep -F 'ResGraph.Authorization.raiseError(Security.onForbidden(reason, ~ctx=ctx grep -F 'switch Security.canReadNamed(Obj.magic(src)' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.first' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.Alias.second' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null +if [[ "$(grep -c 'switch Security.canLoadSelection' "$tmp_dir/valid/ResGraphSchema.res")" -ne 1 ]]; then + echo "Ancestor policy was not emitted exactly once at its declared field." >&2 + exit 1 +fi diff -u "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ "$tmp_dir/valid/authorization-manifest.json" +jq -e ' + . as $manifest | + ([$manifest.fields[] | select(.disposition == "authorizedByAncestor")] | length) == 9 and + ($manifest.fields[] | select(.coordinate == "OutcomePayload.value") | + .ancestorBoundaries == [{ + "coordinate": "Query.outcomePayload", + "kind": "resolverOutcome", + "resolverOutcome": {"async": false} + }]) and + ($manifest.fields[] | select(.coordinate == "SelectionConnection.label") | + .disposition == "public" and .byAncestor == null) and + ($manifest.fields[] | select(.coordinate == "SharedProtected.value") | + [.ancestorBoundaries[].coordinate] == [ + "Query.firstShared", + "Query.secondShared" + ])' \ + "$tmp_dir/valid/authorization-manifest.json" >/dev/null + +mkdir -p "$tmp_dir/manifest-upgrade" +cp "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" +sed -i.bak 's/"version": 2/"version": 1/' \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" +"$resgraph_bin" generate-schema \ + "$root_dir/tests/authorization/valid/src" \ + "$tmp_dir/manifest-upgrade" false required Security.onForbidden \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" \ + >"$tmp_dir/manifest-upgrade-result.json" +jq -e '.generatedBy == "resgraph" and .version == 2 and .status == "success"' \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" >/dev/null mkdir -p "$tmp_dir/cache-bypass" "$resgraph_bin" generate-schema \ "$root_dir/tests/authorization/invalid/src" \ "$tmp_dir/cache-bypass" false \ >"$tmp_dir/cache-bypass-optional-result.json" +grep -F 'Field `OutcomeOnlyPayload.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/cache-bypass-optional-result.json" >/dev/null "$resgraph_bin" generate-schema \ "$root_dir/tests/authorization/invalid/src" \ "$tmp_dir/cache-bypass" false required - \ @@ -95,6 +131,8 @@ grep -F 'must return `ResGraph.Authorization.outcome' \ grep -F 'Public coverage cannot be combined' "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Mutation field `Mutation.outcomeOnly` requires at least one pre-resolver' \ "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `OutcomeOnlyPayload.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Only one `@gql.public` annotation is allowed per field.' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'requires a reason with at least 3 non-whitespace characters' \ @@ -106,6 +144,20 @@ grep -F 'has source type `Mutation`, but it is applied to `Query`' \ grep -F 'must declare `~args` as a ReScript polymorphic object' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'has invalid `~ctx`' "$tmp_dir/invalid-result.json" >/dev/null +grep -F '`@gql.authorize.byAncestor` cannot be combined with `@gql.authorize(...)`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Only one `@gql.authorize.byAncestor` annotation is allowed' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F '`@gql.authorize.byAncestor` requires a reason with at least 3' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `Query.noAncestor` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `SharedSelection.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `SubscriptionEvent.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F '`@gql.authorize.byAncestor` is currently supported on concrete object types' \ + "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Required authorization coverage does not support subscription field `Subscription.events` yet.' \ "$tmp_dir/invalid-result.json" >/dev/null diff --git a/tests/authorization/valid/expected-authorization-manifest.json b/tests/authorization/valid/expected-authorization-manifest.json index ddb8bd52..164061c9 100644 --- a/tests/authorization/valid/expected-authorization-manifest.json +++ b/tests/authorization/valid/expected-authorization-manifest.json @@ -1,37 +1,53 @@ { "generatedBy": "resgraph", - "version": 1, + "version": 2, "status": "success", "fields": [ - {"coordinate":"DeclaredResultFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"DeclaredResultSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"Device.name","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Device.serial","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"InferredFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"InferredSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"InheritedOutcomeDevice.computed","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"InheritedOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"MultiOutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Plain computed values are public","file":"src/PlainNamed.res","location":"[6:0->6:11]"},"resolverOutcome":null}, - {"coordinate":"MultiOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public on the plain interface","file":"src/PlainNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"Mutation.ping","disposition":"public","mutation":true,"policies":[],"public":{"reason":"Explicitly public mutation used by uptime checks","file":"src/Mutation.res","location":"[6:0->6:11]"},"resolverOutcome":null}, - {"coordinate":"Mutation.update","disposition":"policies","mutation":true,"policies":[{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[3:0->3:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"OutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Concrete override has its own public disposition","file":"src/OutcomeDevice.res","location":"[12:0->12:11]"},"resolverOutcome":null}, - {"coordinate":"OutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"PublicDevice.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Names are public across this interface","file":"src/PublicNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"Query.aliasedAsyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":true}}, - {"coordinate":"Query.aliasedOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"Query.asyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":true}}, - {"coordinate":"Query.asyncValue","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadAsync","provenance":"field:Query.asyncValue","file":"src/Query.res","location":"[17:0->17:14]","async":true}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.declared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.declared","file":"src/Query.res","location":"[44:0->44:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.device","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadDevice","provenance":"field:Query.device","file":"src/Query.res","location":"[20:0->20:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.health","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Health check contains no private data","file":"src/Query.res","location":"[5:0->5:11]"},"resolverOutcome":null}, - {"coordinate":"Query.inferred","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.inferred","file":"src/Query.res","location":"[26:0->26:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.ordered","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:0->23:14]","async":false},{"path":"Security.Alias.second","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:31->23:45]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"resolverOutcome":null} + {"coordinate":"AncestorAlpha.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Union member fields are governed by the query policy","file":"src/AncestorGraph.res","location":"[0:0->0:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.ancestorUnion","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}}]}, + {"coordinate":"AncestorBeta.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Union member fields are governed by the query policy","file":"src/AncestorGraph.res","location":"[7:0->7:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.ancestorUnion","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}}]}, + {"coordinate":"DeclaredResultFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"DeclaredResultSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Device.name","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Device.serial","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InferredFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InferredSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InheritedOutcomeDevice.computed","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"InheritedOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"MultiOutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Plain computed values are public","file":"src/PlainNamed.res","location":"[6:0->6:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"MultiOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public on the plain interface","file":"src/PlainNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Mutation.ping","disposition":"public","mutation":true,"policies":[],"public":{"reason":"Explicitly public mutation used by uptime checks","file":"src/Mutation.res","location":"[13:0->13:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Mutation.update","disposition":"policies","mutation":true,"policies":[{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[10:0->10:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Concrete override has its own public disposition","file":"src/OutcomeDevice.res","location":"[12:0->12:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomePayload.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Payload is exposed only after its resolver outcome allows access","file":"src/SelectionCoverage.res","location":"[31:0->31:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.outcomePayload","kind":"resolverOutcome","resolverOutcome":{"async":false}}]}, + {"coordinate":"PublicDevice.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Names are public across this interface","file":"src/PublicNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.aliasedAsyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":true}}, + {"coordinate":"Query.aliasedOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.ancestorUnion","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.asyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":true}}, + {"coordinate":"Query.asyncValue","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadAsync","provenance":"field:Query.asyncValue","file":"src/Query.res","location":"[17:0->17:14]","async":true}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.declared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.declared","file":"src/Query.res","location":"[44:0->44:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.device","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadDevice","provenance":"field:Query.device","file":"src/Query.res","location":"[20:0->20:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.firstShared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.firstShared","file":"src/AncestorGraph.res","location":"[27:0->27:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.health","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Health check contains no private data","file":"src/Query.res","location":"[5:0->5:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.inferred","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.inferred","file":"src/Query.res","location":"[26:0->26:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.ordered","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:0->23:14]","async":false},{"path":"Security.Alias.second","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:31->23:45]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.outcomePayload","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.secondShared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.secondShared","file":"src/AncestorGraph.res","location":"[30:0->30:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionConnection.edges","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural connection fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[20:0->20:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionConnection.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Static label contains no protected data","file":"src/SelectionCoverage.res","location":"[27:2->27:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionEdge.cursor","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural edge fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[11:0->11:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionEdge.node","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural edge fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[11:0->11:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionNode.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"field:SelectionNode.secret","file":"src/SelectionCoverage.res","location":"[7:2->7:16]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionNode.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Value has no authorization identity beyond its selection result","file":"src/SelectionCoverage.res","location":"[2:2->2:27]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SharedProtected.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Shared result fields are protected on every entry path","file":"src/AncestorGraph.res","location":"[20:0->20:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.firstShared","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.firstShared","file":"src/AncestorGraph.res","location":"[27:0->27:14]","async":false}},{"coordinate":"Query.secondShared","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.secondShared","file":"src/AncestorGraph.res","location":"[30:0->30:14]","async":false}}]}, + {"coordinate":"UpdatePayload.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Mutation payload fields are governed by the mutation policy","file":"src/Mutation.res","location":"[3:0->3:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Mutation.update","kind":"policy","policy":{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[10:0->10:14]","async":false}}]}, + {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null} ] } diff --git a/tests/authorization/valid/src/AncestorGraph.res b/tests/authorization/valid/src/AncestorGraph.res new file mode 100644 index 00000000..bec2a1cd --- /dev/null +++ b/tests/authorization/valid/src/AncestorGraph.res @@ -0,0 +1,32 @@ +@gql.authorize.byAncestor({reason: "Union member fields are governed by the query policy"}) +@gql.type +type ancestorAlpha = { + @gql.field + value: string, +} + +@gql.authorize.byAncestor({reason: "Union member fields are governed by the query policy"}) +@gql.type +type ancestorBeta = { + @gql.field + value: string, +} + +@gql.union +type ancestorResult = Alpha(ancestorAlpha) | Beta(ancestorBeta) + +@gql.authorize(Security.first) @gql.field +let ancestorUnion = (_: Query.query): ancestorResult => Alpha({value: "alpha"}) + +@gql.authorize.byAncestor({reason: "Shared result fields are protected on every entry path"}) +@gql.type +type sharedProtected = { + @gql.field + value: string, +} + +@gql.authorize(Security.first) @gql.field +let firstShared = (_: Query.query): sharedProtected => {value: "first"} + +@gql.authorize(Security.first) @gql.field +let secondShared = (_: Query.query): sharedProtected => {value: "second"} diff --git a/tests/authorization/valid/src/Mutation.res b/tests/authorization/valid/src/Mutation.res index 66ef186d..724d4725 100644 --- a/tests/authorization/valid/src/Mutation.res +++ b/tests/authorization/valid/src/Mutation.res @@ -1,8 +1,15 @@ @gql.type type mutation +@gql.authorize.byAncestor({reason: "Mutation payload fields are governed by the mutation policy"}) +@gql.type +type updatePayload = { + @gql.field + value: string, +} + @gql.authorize(Security.canMutate) @gql.field -let update = (_: mutation, ~value: string): string => value +let update = (_: mutation, ~value: string): updatePayload => {value: value} @gql.public({reason: "Explicitly public mutation used by uptime checks"}) @gql.field let ping = (_: mutation): bool => true diff --git a/tests/authorization/valid/src/Query.res b/tests/authorization/valid/src/Query.res index d5680c4b..e0d95fa2 100644 --- a/tests/authorization/valid/src/Query.res +++ b/tests/authorization/valid/src/Query.res @@ -44,3 +44,15 @@ type declaredResult = Success({value: string}) | Failure({message: string}) @gql.authorize(Security.first) @gql.field let declared = (_: query): declaredResult => Success({value: "visible"}) + +@gql.authorize(Security.canLoadSelection) @gql.field +let selection = (_: query): SelectionCoverage.selectionConnection => { + edges: [{cursor: "cursor", node: {value: "selected", secret: "secret"}}], + label: "selection", +} + +@gql.field +let outcomePayload = (_: query): ResGraph.Authorization.outcome< + SelectionCoverage.outcomePayload, + string, +> => ResGraph.Authorization.Allowed({value: "outcome protected"}) diff --git a/tests/authorization/valid/src/Security.res b/tests/authorization/valid/src/Security.res index 4a783bdd..d053585f 100644 --- a/tests/authorization/valid/src/Security.res +++ b/tests/authorization/valid/src/Security.res @@ -40,3 +40,8 @@ module Alias = Nested let canLoadPublicDevice = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() let canLoadOutcomeDevice = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() + +let canLoadSelection = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() + +let canReadSelectionNode = (_: SelectionCoverage.selectionNode, ~args) => + ResGraph.Authorization.Allowed() diff --git a/tests/authorization/valid/src/SelectionCoverage.res b/tests/authorization/valid/src/SelectionCoverage.res new file mode 100644 index 00000000..6246f0a2 --- /dev/null +++ b/tests/authorization/valid/src/SelectionCoverage.res @@ -0,0 +1,39 @@ +@gql.type +type selectionNode = { + @gql.authorize.byAncestor({ + reason: "Value has no authorization identity beyond its selection result", + }) + @gql.field + value: string, + @gql.authorize(Security.canReadSelectionNode) @gql.field + secret: string, +} + +@gql.authorize.byAncestor({reason: "Structural edge fields are governed by the selection query"}) +@gql.type +type selectionEdge = { + @gql.field + cursor: string, + @gql.field + node: selectionNode, +} + +@gql.authorize.byAncestor({ + reason: "Structural connection fields are governed by the selection query", +}) +@gql.type +type selectionConnection = { + @gql.field + edges: array, + @gql.public({reason: "Static label contains no protected data"}) @gql.field + label: string, +} + +@gql.authorize.byAncestor({ + reason: "Payload is exposed only after its resolver outcome allows access", +}) +@gql.type +type outcomePayload = { + @gql.field + value: string, +}