Skip to content

Commit

Permalink
some logging
Browse files Browse the repository at this point in the history
  • Loading branch information
n1ru4l committed Oct 31, 2024
1 parent 31b7563 commit 3cb65ba
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 23 deletions.
3 changes: 2 additions & 1 deletion packages/services/api/src/modules/auth/lib/authz.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { AccessError } from '../../../shared/errors';
import { NoopLogger } from '../../shared/providers/logger';
import { AuthorizationPolicyStatement, Session } from './authz';

class TestSession extends Session {
policyStatements: Array<AuthorizationPolicyStatement>;
constructor(policyStatements: Array<AuthorizationPolicyStatement>) {
super();
super({ logger: new NoopLogger() });
this.policyStatements = policyStatements;
}

Expand Down
39 changes: 38 additions & 1 deletion packages/services/api/src/modules/auth/lib/authz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FastifyReply, FastifyRequest } from '@hive/service-common';
import type { User } from '../../../shared/entities';
import { AccessError } from '../../../shared/errors';
import { isUUID } from '../../../shared/is-uuid';
import { Logger } from '../../shared/providers/logger';

export type AuthorizationPolicyStatement = {
effect: 'allow' | 'deny';
Expand Down Expand Up @@ -56,6 +57,13 @@ export abstract class Session {
Promise<AuthorizationPolicyStatement[]> | Array<AuthorizationPolicyStatement>
>();
private performActionCache = new Map<string, Promise<void>>();
protected logger: Logger;

constructor(args: { logger: Logger }) {
this.logger = args.logger.child({
module: this.constructor.name,
});
}

/** Load policy statements for a specific organization. */
protected abstract loadPolicyStatementsForOrganization(
Expand Down Expand Up @@ -97,9 +105,22 @@ export abstract class Session {
organizationId: string;
params: Parameters<(typeof actionDefinitions)[TAction]>[0];
}): Promise<void> {
this.logger.debug(
'Assert performing action (action=%s, organizationId=%s, params=%o)',
args.action,
args.organizationId,
args.params,
);

const argsStr = stringify(args);
let result = this.performActionCache.get(argsStr);
if (result !== undefined) {
this.logger.debug(
'Serve result from cache (action=%s, organizationId=%s, params=%o)',
args.action,
args.organizationId,
args.params,
);
return result;
}
result = this._assertPerformAction(args);
Expand Down Expand Up @@ -151,6 +172,12 @@ export abstract class Session {
for (const action of actions) {
if (isActionMatch(action, args.action)) {
if (permission.effect === 'deny') {
this.logger.debug(
'Session not authorized to perform action. Action explicitly denied. (action=%s, organizationId=%s, params=%o)',
args.action,
args.organizationId,
args.params,
);
throw new AccessError(`Missing permission for performing '${args.action}' on resource`);
} else {
isAllowed = true;
Expand All @@ -160,6 +187,13 @@ export abstract class Session {
}

if (!isAllowed) {
this.logger.debug(
'Session not authorized to perform action. Action not allowed. (action=%s, organizationId=%s, params=%o)',
args.action,
args.organizationId,
args.params,
);

throw new AccessError(`Missing permission for performing '${args.action}' on resource`);
}
}
Expand All @@ -185,6 +219,7 @@ export abstract class Session {

/** Reset the permissions cache. */
public reset() {
this.logger.debug('Reset cache.');
this.performActionCache.clear();
this.policyStatementCache.clear();
}
Expand Down Expand Up @@ -390,6 +425,8 @@ export class AuthN {
}
}

return new UnauthenticatedSession();
return new UnauthenticatedSession({
logger: args.req.log,
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { captureException } from '@sentry/node';
import type { User } from '../../../shared/entities';
import { AccessError, HiveError } from '../../../shared/errors';
import { isUUID } from '../../../shared/is-uuid';
import { Logger } from '../../shared/providers/logger';
import type { Storage } from '../../shared/providers/storage';
import {
OrganizationAccessScope,
Expand All @@ -17,8 +18,11 @@ export class SuperTokensCookieBasedSession extends Session {
public superTokensUserId: string;
private storage: Storage;

constructor(args: { superTokensUserId: string; email: string }, deps: { storage: Storage }) {
super();
constructor(
args: { superTokensUserId: string; email: string },
deps: { storage: Storage; logger: Logger },
) {
super({ logger: deps.logger });
this.superTokensUserId = args.superTokensUserId;
this.storage = deps.storage;
}
Expand Down Expand Up @@ -156,6 +160,7 @@ export class SuperTokensUserAuthNStrategy extends AuthNStrategy<SuperTokensCooki
},
{
storage: this.storage,
logger: args.req.log,
},
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { FastifyReply, FastifyRequest, ServiceLogger } from '@hive/service-common';
import { Logger } from '../../shared/providers/logger';
import { TokenStorage } from '../../token/providers/token-storage';
import { TokensConfig } from '../../token/providers/tokens';
import {
Expand All @@ -16,14 +17,19 @@ export class TargetAccessTokenSession extends Session {

private policies: Array<AuthorizationPolicyStatement>;

constructor(args: {
organizationId: string;
projectId: string;
targetId: string;
token: string;
policies: Array<AuthorizationPolicyStatement>;
}) {
super();
constructor(
args: {
organizationId: string;
projectId: string;
targetId: string;
token: string;
policies: Array<AuthorizationPolicyStatement>;
},
deps: {
logger: Logger;
},
) {
super({ logger: deps.logger });
this.organizationId = args.organizationId;
this.projectId = args.projectId;
this.targetId = args.targetId;
Expand Down Expand Up @@ -115,19 +121,24 @@ export class TargetAccessTokenStrategy extends AuthNStrategy<TargetAccessTokenSe

const result = await tokens.getToken({ token: accessToken });

return new TargetAccessTokenSession({
organizationId: result.organization,
projectId: result.project,
targetId: result.target,
token: accessToken,
policies: transformAccessTokenLegacyScopes({
return new TargetAccessTokenSession(
{
organizationId: result.organization,
projectId: result.project,
targetId: result.target,
scopes: result.scopes as Array<
OrganizationAccessScope | ProjectAccessScope | TargetAccessScope
>,
}),
});
token: accessToken,
policies: transformAccessTokenLegacyScopes({
organizationId: result.organization,
targetId: result.target,
scopes: result.scopes as Array<
OrganizationAccessScope | ProjectAccessScope | TargetAccessScope
>,
}),
},
{
logger: args.req.log,
},
);
}
}

Expand Down
12 changes: 12 additions & 0 deletions packages/services/api/src/modules/shared/providers/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,15 @@ export class Logger {
debug: LogFn = notImplemented('debug');
child: (bindings: Record<string, unknown>) => Logger = notImplemented('child');
}

function noop() {}

export class NoopLogger extends Logger {
info = noop;
warn = noop;
error = noop;
fatal = noop;
trace = noop;
debug = noop;
child = () => this;
}

0 comments on commit 3cb65ba

Please sign in to comment.