Skip to content

Commit

Permalink
fix: semantic-release issues write perms
Browse files Browse the repository at this point in the history
  • Loading branch information
devthejo committed Dec 16, 2024
1 parent 844fc12 commit 083cad2
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 62 deletions.
91 changes: 44 additions & 47 deletions packages/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { createAppAuth } from '@octokit/auth-app';
import { request } from '@octokit/request';
import pRetry from 'p-retry';
import pino from 'pino';
import pinoHttp from 'pino-http';
import config from './config.js';

// Initialize logger
Expand All @@ -14,24 +13,40 @@ const logger = pino(config.logger);
const app = express();
const port = config.port;

// Add request logging middleware
app.use(pinoHttp({
logger,
autoLogging: {
ignore: (req) => req.url === '/health' || req.url === '/'
},
customLogLevel: function (res, err) {
if (res.statusCode >= 400 && res.statusCode < 500) return 'warn'
if (res.statusCode >= 500 || err) return 'error'
return 'info'
},
customSuccessMessage: function (res) {
return `request completed with status ${res.statusCode}`
},
customErrorMessage: function (error, res) {
return `request failed with status ${res.statusCode}: ${error.message}`
// Custom request logging middleware
app.use((req, res, next) => {
// Skip logging for health checks
if (req.url === '/health' || req.url === '/') {
return next();
}
}));

const startTime = Date.now();
const requestId = Math.random().toString(36).substring(2, 15);

// Log request
logger.info({
requestId,
method: req.method,
url: req.url,
ip: req.ip
}, 'Incoming request');

// Log response
res.on('finish', () => {
const duration = Date.now() - startTime;
const level = res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info';

logger[level]({
requestId,
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration: `${duration}ms`
}, 'Request completed');
});

next();
});

// Middleware
app.use(express.json());
Expand Down Expand Up @@ -137,7 +152,6 @@ async function generateToken(owner, repository) {
permissions: {
contents: "write",
metadata: "read",
// issues: "write" // Added issues permission
}
});

Expand All @@ -161,12 +175,8 @@ async function generateToken(owner, repository) {
} catch (error) {
logger.error({
error: error.message,
response: error.response ? {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data,
url: error.response.url
} : undefined
status: error.status,
statusText: error.response?.statusText
}, 'Error in token generation');
throw error;
}
Expand All @@ -179,7 +189,7 @@ function extractAndDecodeToken(authHeader) {

let tokenPayload = authHeader.split(' ')[1];

logger.debug({ tokenPayload }, 'Raw token payload received');
logger.debug('Token payload received');

// Try to parse as JSON first
try {
Expand All @@ -206,23 +216,11 @@ function extractAndDecodeToken(authHeader) {

// Route to generate GitHub App token
app.post('/generate-token', async (req, res) => {
const reqLog = req.log;

try {
reqLog.debug({ auth: req.headers.authorization }, 'Processing token generation request');
logger.debug('Processing token generation request');

const tokenPayload = extractAndDecodeToken(req.headers.authorization);

try {
const [header, payload] = tokenPayload.split('.').slice(0, 2);
reqLog.debug({
header: JSON.parse(Buffer.from(header, 'base64').toString()),
payload: JSON.parse(Buffer.from(payload, 'base64').toString())
}, 'Decoded token parts');
} catch (error) {
reqLog.error({ error }, 'Error decoding token parts');
}

// Verify OIDC token
jwt.verify(tokenPayload, getKey, {
issuer: 'https://token.actions.githubusercontent.com',
Expand All @@ -231,23 +229,22 @@ app.post('/generate-token', async (req, res) => {
clockTolerance: 60 // Allow 1 minute clock skew
}, async (err, decoded) => {
if (err) {
reqLog.error({ err }, 'Token verification failed');
logger.error({ error: err.message }, 'Token verification failed');
return res.status(403).json({
error: 'Token verification failed',
details: err.message
});
}

reqLog.debug({ decoded }, 'Token verified successfully');
logger.debug('Token verified successfully');

// Extract repository information from the token
const repo = decoded.repository;
const repoOwner = decoded.repository_owner;

if (!repo || !repoOwner) {
return res.status(400).json({
error: 'Missing repository information in token',
claims: decoded
error: 'Missing repository information in token'
});
}

Expand All @@ -258,26 +255,26 @@ app.post('/generate-token', async (req, res) => {
{
retries: 0,
onFailedAttempt: error => {
reqLog.error({
logger.error({
attempt: error.attemptNumber,
error: error.message
}, 'Failed to generate token');
}
}
);

reqLog.info('Token generated successfully');
logger.info('Token generated successfully');
return res.json(result);
} catch (error) {
reqLog.error({ error }, 'Error generating token');
logger.error({ error: error.message }, 'Error generating token');
return res.status(500).json({
error: 'Failed to generate token',
details: error.message
});
}
});
} catch (error) {
reqLog.error({ error }, 'Error processing request');
logger.error({ error: error.message }, 'Error processing request');
return res.status(400).json({
error: 'Failed to decode token',
details: error.message
Expand Down
1 change: 0 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"jwks-rsa": "^3.1.0",
"p-retry": "^6.2.1",
"pino": "^9.5.0",
"pino-http": "^10.3.0",
"pino-pretty": "^13.0.0"
}
}
15 changes: 1 addition & 14 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2976,18 +2976,6 @@ __metadata:
languageName: node
linkType: hard

"pino-http@npm:^10.3.0":
version: 10.3.0
resolution: "pino-http@npm:10.3.0"
dependencies:
get-caller-file: "npm:^2.0.5"
pino: "npm:^9.0.0"
pino-std-serializers: "npm:^7.0.0"
process-warning: "npm:^4.0.0"
checksum: 10c0/da95d93e1176c02201f9b9bb0af53ad737105c5772acbb077dcad0f52ebce2438e0e9fc8216cd96396d1305d0ecf1f1d23142c7a50110a701ea093b2ee999ea7
languageName: node
linkType: hard

"pino-pretty@npm:^13.0.0":
version: 13.0.0
resolution: "pino-pretty@npm:13.0.0"
Expand Down Expand Up @@ -3018,7 +3006,7 @@ __metadata:
languageName: node
linkType: hard

"pino@npm:^9.0.0, pino@npm:^9.5.0":
"pino@npm:^9.5.0":
version: 9.5.0
resolution: "pino@npm:9.5.0"
dependencies:
Expand Down Expand Up @@ -3842,7 +3830,6 @@ __metadata:
jwks-rsa: "npm:^3.1.0"
p-retry: "npm:^6.2.1"
pino: "npm:^9.5.0"
pino-http: "npm:^10.3.0"
pino-pretty: "npm:^13.0.0"
languageName: unknown
linkType: soft
Expand Down

0 comments on commit 083cad2

Please sign in to comment.