Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow jwt in param injection (policy authorization can use it through… #144

Merged
merged 1 commit into from
Jun 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ lerna-debug.log*

node_modules/
*.tsbuildinfo
.yarn-integrity
.yarn-integrity
22 changes: 13 additions & 9 deletions docs/authorization_spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ metadata:
name: abc-user
Spec:
type: js-expression
code: { "result": (data.jwt.issuer === "abc.com") ? "allow" : "deny" }
code: { "result": (input.args.issuer === "abc.com") ? "allow" : "deny" }
args:
issuer: String!
```

`jwt` is available on the data object to validate fields from the web token
The `args` are available to use on the input object.
`jwt` is available for parameter injection in args using `issuer: "{jwt.issuer}"`

### Policy that allows access only if the subject matches the provided userId argument:

Expand All @@ -51,13 +54,12 @@ metadata:
name: my-user
Spec:
type: js-expression
code: { "result": (input.jwt.sub === input.args.userId) ? "allow" : "deny"}
code: { "result": (input.args.sub === input.args.userId) ? "allow" : "deny"}
args:
userId: ID!
sub: ID!
```

The `args` are available to use on the input object

_Note the js-expression type is an example of a possible type and not planned to be implemented at this time._

### Policy that uses a graphql query to fetch additional data and allows based on the results and an argument:
Expand Down Expand Up @@ -104,13 +106,14 @@ metadata:
Spec:
type: opa
code: |
query = sprintf(“graphql { user(%s) {family { members { id} } } }”, input.jwt.sub)
query = sprintf(“graphql { user(%s) {family { members { id} } } }”, input.args.sub)
allow = false
allow = {
input.args.userId == input.query.family.members[_].id
}
args:
userId: ID!
sub: ID!
```

This example will always evaluate the graphql query, but generally this approach should be used when conditional side effect evaluation is needed
Expand Down Expand Up @@ -149,7 +152,7 @@ type User {
ID: ID!
Picture: String @policy-some-ns-public
Friends: [User] @policy-some-ns-abc-user
Email: String @policy-some-ns-my-user(userId: "{source.UserId}")
Email: String @policy-some-ns-my-user(userId: "{source.UserId}", sub: "{jwt.sub}")
NickName: @policy-some-ns-my-user-family(userId: "{source.UserId}")
}
```
Expand Down Expand Up @@ -267,18 +270,19 @@ Spec:
code: |
allow = false
allow {
input.jwt.claims[input.args.claims[i]] == input.args.values[i]
input.args.jwtClaims[input.args.claims[i]] == input.args.values[i]
}
args:
claims: [String]
values: [String]
jwtClaims: JSONObject
```

Usage:

```
type User {
ID: ID!
Picture: String @policy-some-ns-has-claims(claims:["issuer", "sub"], values: ["soluto.com", "{source.UserId}"]
Picture: String @policy-some-ns-has-claims(claims:["issuer", "sub"], values: ["soluto.com", "{source.UserId}"], jwtClaims: "{jwt.claims}")
}
```
93 changes: 93 additions & 0 deletions services/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions services/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"graphql-iso-date": "^3.6.1",
"graphql-tools": "^4.0.7",
"graphql-type-json": "^0.3.1",
"jsonwebtoken": "^8.5.1",
"node-cache": "^5.1.0",
"node-fetch": "^2.6.0",
"openid-client": "^3.13.0",
Expand All @@ -42,6 +43,7 @@
"@types/graphql-iso-date": "^3.3.3",
"@types/graphql-type-json": "^0.3.2",
"@types/jest": "^25.1.3",
"@types/jsonwebtoken": "^8.5.0",
"@types/node": "^13.7.4",
"@types/pino": "^5.15.5",
"@types/xml2js": "^0.4.5",
Expand Down
4 changes: 1 addition & 3 deletions services/src/modules/directives/policy/opa.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-ignore opa-wasm already has TS typings merged, but not yet published on npm
import * as Rego from '@open-policy-agent/opa-wasm';
import {getCompiledFilename} from '../../opaHelper';
import {PolicyExecutionContext, PolicyExecutionResult, QueriesResults, JwtInput} from './types';
import {PolicyExecutionContext, PolicyExecutionResult, QueriesResults} from './types';
import {PolicyArgsObject} from '../../resource-repository';

export async function evaluate(ctx: PolicyExecutionContext): Promise<PolicyExecutionResult> {
Expand All @@ -24,15 +24,13 @@ async function getWasmPolicy(ctx: PolicyExecutionContext): Promise<any> {
function getInput(ctx: PolicyExecutionContext): PolicyInput {
const input: PolicyInput = {};

if (ctx.jwt) input.jwt = ctx.jwt;
if (ctx.args) input.args = ctx.args;
if (ctx.queries) input.queries = ctx.queries;

return input;
}

type PolicyInput = {
jwt?: JwtInput;
args?: PolicyArgsObject;
queries?: QueriesResults;
};
7 changes: 5 additions & 2 deletions services/src/modules/directives/policy/policy-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export class PolicyExecutor {
protected context: RequestContext,
protected info: GraphQLResolveInfo
) {
// TODO: add jwt data
this.policyDefinitions = context.policies;
this.policyAttachments = context.policyAttachments;
}
Expand All @@ -38,7 +37,11 @@ export class PolicyExecutor {
const evaluate = typeEvaluators[policyDefinition.type];
if (!evaluate) throw new Error(`Unsupported policy type ${policyDefinition.type}`);

const {done, allow} = await evaluate({...policy, args, policyAttachments: this.policyAttachments});
const {done, allow} = await evaluate({
...policy,
args,
policyAttachments: this.policyAttachments,
});
if (!done) throw new Error('in-line query evaluation not yet supported');

if (!allow) throw new Error(`Unauthorized by policy ${policy.name} in namespace ${policy.namespace}`);
Expand Down
5 changes: 0 additions & 5 deletions services/src/modules/directives/policy/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export type PolicyExecutionContext = {
namespace: string;
name: string;
policyAttachments: PolicyAttachments;
jwt?: JwtInput;
args?: PolicyArgsObject;
queries?: QueriesResults;
};
Expand All @@ -20,10 +19,6 @@ export type QueriesResults = {
[name: string]: string;
};

export type JwtInput = {
[name: string]: string;
};

export type PolicyExecutionResult = {
done: boolean;
allow?: boolean;
Expand Down
30 changes: 30 additions & 0 deletions services/src/modules/paramInjection.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import {GraphQLResolveInfo} from 'graphql';
import {decode as decodeJwt} from 'jsonwebtoken';
import {RequestContext} from './context';

interface GraphQLArguments {
[key: string]: any;
}
type jwtData = {
[name: string]: any;
};

const paramRegex = /{(\w+\.\w+)}/g;
const authzHeaderPrefix = 'Bearer ';

function resolveTemplate(
template: string,
Expand All @@ -22,6 +28,8 @@ function resolveTemplate(
return args && args[propName];
case 'exports':
return context.exports.resolve(info.parentType, parent, propName);
case 'jwt':
return getJwt(context)[propName];
default:
return null;
}
Expand Down Expand Up @@ -96,3 +104,25 @@ export function deepInjectParameters(
function isObject(val: any): val is object {
return typeof val === 'object' && val !== null;
}

function getJwt(context: RequestContext): jwtData {
if (context.jwt) return context.jwt;

const authzHeader = context?.request?.headers?.authorization;

context.jwt = isAuthzHeaderValid(authzHeader)
? (decodeJwt(authzHeader.substr(authzHeaderPrefix.length), {json: true}) as jwtData)
: {};

return context.jwt;
}

function isAuthzHeaderValid(authzHeader: any): boolean {
return authzHeader && authzHeader.startsWith(authzHeaderPrefix);
}

declare module './context' {
interface RequestContext {
jwt?: jwtData;
}
}
1 change: 1 addition & 0 deletions services/src/tests/e2e/jest-e2e-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class SerialJestRunner extends DefaultJestRunner {
}

async teardown() {
// await dockerCompose.logs(['gateway', 'registry'], {cwd: __dirname, log: true});
await dockerCompose.down({cwd: __dirname, log: true});
await Promise.all([waitFor.gatewayStop(10000), waitFor.registryStop(10000)]);
}
Expand Down
Loading