private void setState(State state) { synchronized (lock) { this.state = state; this.lastActivityAt = clock.currentTimeMillis(); } }
/** Return current time according to {@code reader}. */ private static long now(PubsubReader reader) { if (reader.outer.outer.clock == null) { return System.currentTimeMillis(); } else { return reader.outer.outer.clock.currentTimeMillis(); } }
/** Return the current time, in ms since epoch. */ private long now() { if (outer.outer.clock == null) { return System.currentTimeMillis(); } else { return outer.outer.clock.currentTimeMillis(); } }
/** * Add a key and value representing the current time, as determined by the passed clock, to the * passed attributes dictionary. * @param attributes The file attributes map to update * @param clock The clock to retrieve the current time from */ public static void addModificationTimeToAttributes(Map<String, byte[]> attributes, Clock clock) { attributes.put(FILE_MODIFICATION_TIMESTAMP_KEY, Longs.toByteArray(clock.currentTimeMillis())); }
CacheState getCacheState() { long now = clock.currentTimeMillis(); if (!token.status.isOk()) { return CacheState.Exception; } else if (actualExpirationTimeMs - TOKEN_EXPIRES_MS <= now) { return CacheState.Expired; } else if (actualExpirationTimeMs - TOKEN_STALENESS_MS <= now) { return CacheState.Stale; } else { return CacheState.Good; } }
/** * Return the remaining time the current access token will be valid, or null if there is no * token or expiry information. Must be called under lock. */ private Long getExpiresInMilliseconds() { if (temporaryAccess == null) { return null; } Date expirationTime = temporaryAccess.getExpirationTime(); if (expirationTime == null) { return null; } return (expirationTime.getTime() - clock.currentTimeMillis()); }
/** * Return the remaining time the current access token will be valid, or null if there is no * token or expiry information. Must be called under lock. */ private Long getExpiresInMilliseconds() { if (temporaryAccess == null) { return null; } Date expirationTime = temporaryAccess.getExpirationTime(); if (expirationTime == null) { return null; } return (expirationTime.getTime() - clock.currentTimeMillis()); }
@Override public synchronized void create(String bucketName, CreateBucketOptions options) throws IOException { if (!validateBucketName(bucketName)) { throw new IOException("Error creating bucket. Invalid name: " + bucketName); } if (!bucketLookup.containsKey(bucketName)) { bucketLookup.put( bucketName, new InMemoryBucketEntry(bucketName, clock.currentTimeMillis(), options)); } else { throw new IOException("Bucket '" + bucketName + "'already exists"); } }
/** * Returns an unmodifiable view of the public keys. * * <p> * For efficiency, an in-memory cache of the public keys is used here. If this method is called * for the first time, or the certificates have expired since last time it has been called (or are * within 5 minutes of expiring), {@link #refresh()} will be called before returning the value. * </p> */ public final List<PublicKey> getPublicKeys() throws GeneralSecurityException, IOException { lock.lock(); try { if (publicKeys == null || clock.currentTimeMillis() + REFRESH_SKEW_MILLIS > expirationTimeMilliseconds) { refresh(); } return publicKeys; } finally { lock.unlock(); } }
/** * For subscription mode only: Track progression of time according to the {@link Clock} passed . * This will simulate Pubsub expiring outstanding ACKs. */ public void advance() { synchronized (STATE) { checkState(inPullMode(), "Can only advance in pull mode"); // Any messages who's ACKs timed out are available for re-pulling. Iterator<Map.Entry<String, Long>> deadlineItr = STATE.ackDeadline.entrySet().iterator(); while (deadlineItr.hasNext()) { Map.Entry<String, Long> entry = deadlineItr.next(); if (entry.getValue() <= STATE.clock.currentTimeMillis()) { STATE.remainingPendingIncomingMessages.add( STATE.pendingAckIncomingMessages.remove(entry.getKey())); deadlineItr.remove(); } } } }
int expiresInSeconds = OAuth2Utils.validateInt32( responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
@Override protected TokenResponse executeRefreshToken() throws IOException { accessTokenProvider.refresh(); AccessToken accessToken = Preconditions.checkNotNull( accessTokenProvider.getAccessToken(), "Access Token cannot be null!"); String token = Preconditions.checkNotNull(accessToken.getToken(), "Access Token cannot be null!"); Long expirationTimeMilliSeconds = accessToken.getExpirationTimeMilliSeconds(); return new TokenResponse() .setAccessToken(token) .setExpiresInSeconds( expirationTimeMilliSeconds == null ? null : (expirationTimeMilliSeconds - clock.currentTimeMillis()) / 1000); } }
public String createSignedCustomAuthTokenForUser( String uid, Map<String, Object> developerClaims) throws IOException { checkArgument(!Strings.isNullOrEmpty(uid), "Uid must be provided."); checkArgument(uid.length() <= 128, "Uid must be shorter than 128 characters."); JsonWebSignature.Header header = new JsonWebSignature.Header().setAlgorithm("RS256"); final long issuedAt = clock.currentTimeMillis() / 1000; FirebaseCustomAuthToken.Payload payload = new FirebaseCustomAuthToken.Payload() .setUid(uid) .setIssuer(signer.getAccount()) .setSubject(signer.getAccount()) .setAudience(FirebaseCustomAuthToken.FIREBASE_AUDIENCE) .setIssuedAtTimeSeconds(issuedAt) .setExpirationTimeSeconds(issuedAt + FirebaseCustomAuthToken.TOKEN_DURATION_SECONDS); if (developerClaims != null) { Collection<String> reservedNames = payload.getClassInfo().getNames(); for (String key : developerClaims.keySet()) { if (reservedNames.contains(key)) { throw new IllegalArgumentException( String.format("developerClaims must not contain a reserved key: %s", key)); } } GenericJson jsonObject = new GenericJson(); jsonObject.putAll(developerClaims); payload.setDeveloperClaims(jsonObject); } return signPayload(header, payload); }
private String generateJwtAccess(URI uri) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = clock.currentTimeMillis(); // Both copies of the email are required payload.setIssuer(clientEmail); payload.setSubject(clientEmail); payload.setAudience(uri.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + LIFE_SPAN_SECS); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException("Error signing service account JWT access header with private key.", e); } return assertion; }
private String generateJwtAccess(URI uri) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = clock.currentTimeMillis(); // Both copies of the email are required payload.setIssuer(clientEmail); payload.setSubject(clientEmail); payload.setAudience(uri.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + LIFE_SPAN_SECS); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException("Error signing service account JWT access header with private key.", e); } return assertion; }
/** * Refreshes the OAuth2 access token by getting a new access token from the refresh token */ @Override public AccessToken refreshAccessToken() throws IOException { if (refreshToken == null) { throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token."); } GenericData tokenRequest = new GenericData(); tokenRequest.set("client_id", clientId); tokenRequest.set("client_secret", clientSecret); tokenRequest.set("refresh_token", refreshToken); tokenRequest.set("grant_type", GRANT_TYPE); UrlEncodedContent content = new UrlEncodedContent(tokenRequest); HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content); request.setParser(new JsonObjectParser(JSON_FACTORY)); HttpResponse response = request.execute(); GenericData responseData = response.parseAs(GenericData.class); String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX); int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; return new AccessToken(accessToken, new Date(expiresAtMilliseconds)); }
/** * Refreshes the OAuth2 access token by getting a new access token from the refresh token */ @Override public AccessToken refreshAccessToken() throws IOException { if (refreshToken == null) { throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token."); } GenericData tokenRequest = new GenericData(); tokenRequest.set("client_id", clientId); tokenRequest.set("client_secret", clientSecret); tokenRequest.set("refresh_token", refreshToken); tokenRequest.set("grant_type", GRANT_TYPE); UrlEncodedContent content = new UrlEncodedContent(tokenRequest); HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content); request.setParser(new JsonObjectParser(JSON_FACTORY)); HttpResponse response = request.execute(); GenericData responseData = response.parseAs(GenericData.class); String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX); int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; return new AccessToken(accessToken, new Date(expiresAtMilliseconds)); }
header.setKeyId(serviceAccountPrivateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = getClock().currentTimeMillis(); payload.setIssuer(serviceAccountId); payload.setAudience(getTokenServerEncodedUrl());
@Test public void createAssertion_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); List<String> scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(scopes) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; long currentTimeMillis = Clock.SYSTEM.currentTimeMillis(); String assertion = credentials.createAssertion(jsonFactory, currentTimeMillis, null); JsonWebSignature signature = JsonWebSignature.parse(jsonFactory, assertion); JsonWebToken.Payload payload = signature.getPayload(); assertEquals(SA_CLIENT_EMAIL, payload.getIssuer()); assertEquals(OAuth2Utils.TOKEN_SERVER_URI.toString(), payload.getAudience()); assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(SERVICE_ACCOUNT_USER, payload.getSubject()); assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); }
@Test public void createAssertion_withTokenUri_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); List<String> scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setScopes(scopes) .setServiceAccountUser(SERVICE_ACCOUNT_USER) .setProjectId(PROJECT_ID) .build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; long currentTimeMillis = Clock.SYSTEM.currentTimeMillis(); String assertion = credentials.createAssertion(jsonFactory, currentTimeMillis, "https://foo.com/bar"); JsonWebSignature signature = JsonWebSignature.parse(jsonFactory, assertion); JsonWebToken.Payload payload = signature.getPayload(); assertEquals(SA_CLIENT_EMAIL, payload.getIssuer()); assertEquals("https://foo.com/bar", payload.getAudience()); assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(SERVICE_ACCOUNT_USER, payload.getSubject()); assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); }