code
stringlengths
73
34.1k
label
stringclasses
1 value
protected List<IPersonAttributes> searchDirectory(String query, PortletRequest request) { final Map<String, Object> queryAttributes = new HashMap<>(); for (String attr : directoryQueryAttributes) { queryAttributes.put(attr, query); } final List<IPersonAttributes> people; // get an authorization principal for the current requesting user HttpServletRequest servletRequest = portalRequestUtils.getPortletHttpRequest(request); IPerson currentUser = personManager.getPerson(servletRequest); // get the set of people matching the search query people = this.lookupHelper.searchForPeople(currentUser, queryAttributes); log.debug( "Directory portlet search outcome:\n\tqueryAttributes=" + queryAttributes + "\n\tsearchResult=" + people); return people; }
java
protected boolean isMobile(PortletRequest request) { final String themeName = request.getProperty(IPortletRenderer.THEME_NAME_PROPERTY); return "UniversalityMobile".equals(themeName); }
java
protected IPortletEntity unwrapEntity(IPortletEntity portletEntity) { if (portletEntity instanceof TransientPortletEntity) { return ((TransientPortletEntity) portletEntity).getDelegatePortletEntity(); } return portletEntity; }
java
protected IPortletEntity wrapEntity(IPortletEntity portletEntity) { if (portletEntity == null) { return null; } final String persistentLayoutNodeId = portletEntity.getLayoutNodeId(); if (persistentLayoutNodeId.startsWith(TransientUserLayoutManagerWrapper.SUBSCRIBE_PREFIX)) { final IUserLayoutManager userLayoutManager = this.getUserLayoutManager(); if (userLayoutManager == null) { this.logger.warn( "Could not find IUserLayoutManager when trying to wrap transient portlet entity: " + portletEntity); return portletEntity; } final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final String fname = portletDefinition.getFName(); final String layoutNodeId = userLayoutManager.getSubscribeId(fname); return new TransientPortletEntity(portletEntity, layoutNodeId); } return portletEntity; }
java
public static boolean isValidUrl(String url) { HttpURLConnection huc = null; boolean isValid = false; try { URL u = new URL(url); huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.connect(); int response = huc.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { throw new IOException( String.format( "URL %s did not return a valid response code while attempting to connect. Expected: %d. Received: %d", url, HttpURLConnection.HTTP_OK, response)); } isValid = true; } catch (IOException e) { logger.warn( "A problem happened while trying to verify url: {} Error Message: {}", url, e.getMessage()); } finally { if (huc != null) { huc.disconnect(); } ; } return isValid; }
java
public static <T> boolean included( T value, Collection<? extends T> includes, Collection<? extends T> excludes) { return (includes.isEmpty() && excludes.isEmpty()) || includes.contains(value) || (includes.isEmpty() && !excludes.contains(value)); }
java
@EventListener public void init(ContextRefreshedEvent event) { idTokenFactory = context.getBean(IdTokenFactory.class); // Make sure we have a guestUsernameSelectors collection & sort it if (guestUsernameSelectors == null) { guestUsernameSelectors = Collections.emptyList(); } Collections.sort(guestUsernameSelectors); }
java
protected boolean handleResourceHeader(String key, String value) { if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) { this.portletResourceOutputHandler.setStatus(Integer.parseInt(value)); return true; } if ("Content-Type".equals(key)) { final ContentType contentType = ContentType.parse(value); final Charset charset = contentType.getCharset(); if (charset != null) { this.portletResourceOutputHandler.setCharacterEncoding(charset.name()); } this.portletResourceOutputHandler.setContentType(contentType.getMimeType()); return true; } if ("Content-Length".equals(key)) { this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value)); return true; } if ("Content-Language".equals(key)) { final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null); if (parts.length > 0) { final String localeStr = parts[0].getValue(); final Locale locale = LocaleUtils.toLocale(localeStr); this.portletResourceOutputHandler.setLocale(locale); return true; } } return false; }
java
@Override public void perform() throws PortalException { // push the change into the PLF if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) { // remove the parm edit ParameterEditManager.removeParmEditDirective(nodeId, name, person); } // push the fragment value into the ILF LPAChangeParameter.changeParameterChild(ilfNode, name, fragmentValue); }
java
@Override public void add(IPermission perm) throws AuthorizationException { Connection conn = null; int rc = 0; try { conn = RDBMServices.getConnection(); String sQuery = getInsertPermissionSql(); PreparedStatement ps = conn.prepareStatement(sQuery); try { primAdd(perm, ps); if (log.isDebugEnabled()) log.debug("RDBMPermissionImpl.add(): " + ps); rc = ps.executeUpdate(); if (rc != 1) { throw new AuthorizationException("Problem adding Permission " + perm); } } finally { ps.close(); } } catch (Exception ex) { log.error("Exception adding permission [" + perm + "]", ex); throw new AuthorizationException("Problem adding Permission " + perm); } finally { RDBMServices.releaseConnection(conn); } }
java
@Override public void delete(IPermission[] perms) throws AuthorizationException { if (perms.length > 0) { try { primDelete(perms); } catch (Exception ex) { log.error("Exception deleting permissions " + Arrays.toString(perms), ex); throw new AuthorizationException( "Exception deleting permissions " + Arrays.toString(perms), ex); } } }
java
@Override public void delete(IPermission perm) throws AuthorizationException { Connection conn = null; try { conn = RDBMServices.getConnection(); String sQuery = getDeletePermissionSql(); PreparedStatement ps = conn.prepareStatement(sQuery); try { primDelete(perm, ps); } finally { ps.close(); } } catch (Exception ex) { log.error("Exception deleting permission [" + perm + "]", ex); throw new AuthorizationException("Problem deleting Permission " + perm, ex); } finally { RDBMServices.releaseConnection(conn); } }
java
private int getPrincipalType(String principalString) { return Integer.parseInt( principalString.substring(0, principalString.indexOf(PRINCIPAL_SEPARATOR))); }
java
private int primDelete(IPermission perm, PreparedStatement ps) throws Exception { ps.clearParameters(); ps.setString(1, perm.getOwner()); ps.setInt(2, getPrincipalType(perm)); ps.setString(3, getPrincipalKey(perm)); ps.setString(4, perm.getActivity()); ps.setString(5, perm.getTarget()); if (log.isDebugEnabled()) log.debug("RDBMPermissionImpl.primDelete(): " + ps); return ps.executeUpdate(); }
java
private int primUpdate(IPermission perm, PreparedStatement ps) throws Exception { java.sql.Timestamp ts = null; // UPDATE COLUMNS: ps.clearParameters(); // TYPE: if (perm.getType() == null) { ps.setNull(1, Types.VARCHAR); } else { ps.setString(1, perm.getType()); } // EFFECTIVE: if (perm.getEffective() == null) { ps.setNull(2, Types.TIMESTAMP); } else { ts = new java.sql.Timestamp(perm.getEffective().getTime()); ps.setTimestamp(2, ts); } // EXPIRES: if (perm.getExpires() == null) { ps.setNull(3, Types.TIMESTAMP); } else { ts = new java.sql.Timestamp(perm.getExpires().getTime()); ps.setTimestamp(3, ts); } // WHERE COLUMNS: ps.setString(4, perm.getOwner()); ps.setInt(5, getPrincipalType(perm)); ps.setString(6, getPrincipalKey(perm)); ps.setString(7, perm.getActivity()); ps.setString(8, perm.getTarget()); if (log.isDebugEnabled()) log.debug("RDBMPermissionImpl.primUpdate(): " + ps); return ps.executeUpdate(); }
java
@Override public IPermission[] select( String owner, String principal, String activity, String target, String type) throws AuthorizationException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<IPermission> perms = new ArrayList<IPermission>(); String query = getSelectQuery(owner, principal, activity, target, type); try { conn = RDBMServices.getConnection(); stmt = conn.prepareStatement(query); prepareSelectQuery(stmt, owner, principal, activity, target, type); try { rs = stmt.executeQuery(); try { while (rs.next()) { perms.add(instanceFromResultSet(rs)); } } finally { rs.close(); } } finally { stmt.close(); } } catch (SQLException sqle) { log.error("Problem retrieving permissions", sqle); throw new AuthorizationException( "Problem retrieving Permissions [" + sqle.getMessage() + "] for query=[" + query + "] for owner=[" + owner + "] and principal=[" + principal + "] and activity=[" + activity + "] and target=[" + target + "] and type=[" + type + "]", sqle); } finally { RDBMServices.releaseConnection(conn); } if (log.isTraceEnabled()) { log.trace( "RDBMPermissionImpl.select(): [" + query + "] for owner=[" + owner + "] and principal=[" + principal + "] and activity=[" + activity + "] and target=[" + target + "] and type=[" + type + "] returned permissions [" + perms + "]"); } return ((IPermission[]) perms.toArray(new IPermission[perms.size()])); }
java
@Override public void update(IPermission perm) throws AuthorizationException { Connection conn = null; try { conn = RDBMServices.getConnection(); String sQuery = getUpdatePermissionSql(); if (log.isDebugEnabled()) log.debug("RDBMPermissionImpl.update(): " + sQuery); PreparedStatement ps = conn.prepareStatement(sQuery); try { primUpdate(perm, ps); } finally { ps.close(); } } catch (Exception ex) { log.error("Exception updating permission [" + perm + "]", ex); throw new AuthorizationException("Problem updating Permission " + perm); } finally { RDBMServices.releaseConnection(conn); } }
java
@Override public PortletEventQueue getPortletEventQueue(HttpServletRequest request) { request = this.portalRequestUtils.getOriginalPortalRequest(request); synchronized (PortalWebUtils.getRequestAttributeMutex(request)) { PortletEventQueue portletEventQueue = (PortletEventQueue) request.getAttribute(PORTLET_EVENT_QUEUE); if (portletEventQueue == null) { portletEventQueue = new PortletEventQueue(); request.setAttribute(PORTLET_EVENT_QUEUE, portletEventQueue); } return portletEventQueue; } }
java
protected HttpServletRequest getServletRequestFromExternalContext( ExternalContext externalContext) { Object request = externalContext.getNativeRequest(); if (request instanceof PortletRequest) { return portalRequestUtils.getPortletHttpRequest( (PortletRequest) externalContext.getNativeRequest()); } else if (request instanceof HttpServletRequest) { return (HttpServletRequest) request; } // give up and throw an error else { throw new IllegalArgumentException( "Unable to recognize the native request associated with the supplied external context"); } }
java
protected IPortletDefinition getChannelDefinition(String subId) throws PortalException { IPortletDefinition chanDef = mChanMap.get(subId); if (null == chanDef) { String fname = getFname(subId); if (log.isDebugEnabled()) log.debug( "TransientUserLayoutManagerWrapper>>getChannelDefinition, " + "attempting to get a channel definition using functional name: " + fname); try { chanDef = PortletDefinitionRegistryLocator.getPortletDefinitionRegistry() .getPortletDefinitionByFname(fname); } catch (Exception e) { throw new PortalException( "Failed to get channel information " + "for subscribeId: " + subId); } mChanMap.put(subId, chanDef); } return chanDef; }
java
@Override public String getSubscribeId(String fname) throws PortalException { // see if a given subscribe id is already in the map String subId = mFnameMap.get(fname); if (subId == null) { // see if a given subscribe id is already in the layout subId = man.getSubscribeId(fname); } // obtain a description of the transient channel and // assign a new transient channel id if (subId == null) { try { IPortletDefinition chanDef = PortletDefinitionRegistryLocator.getPortletDefinitionRegistry() .getPortletDefinitionByFname(fname); if (chanDef != null) { // assign a new id subId = getNextSubscribeId(); mFnameMap.put(fname, subId); mSubIdMap.put(subId, fname); mChanMap.put(subId, chanDef); } } catch (Exception e) { log.error( "TransientUserLayoutManagerWrapper::getSubscribeId() : " + "an exception encountered while trying to obtain " + "ChannelDefinition for fname \"" + fname + "\" : " + e); subId = null; } } return subId; }
java
private IUserLayoutChannelDescription getTransientNode(String nodeId) throws PortalException { // get fname from subscribe id final String fname = getFname(nodeId); if (null == fname || fname.equals("")) { return null; } try { // check cache first IPortletDefinition chanDef = mChanMap.get(nodeId); if (null == chanDef) { chanDef = PortletDefinitionRegistryLocator.getPortletDefinitionRegistry() .getPortletDefinitionByFname(fname); mChanMap.put(nodeId, chanDef); } return createUserLayoutChannelDescription(nodeId, chanDef); } catch (Exception e) { throw new PortalException("Failed to obtain channel definition using fname: " + fname); } }
java
@Override public boolean sendEvent(LrsStatement statement) { if (!isEnabled()) { return false; } ResponseEntity<Object> response = sendRequest( STATEMENTS_REST_ENDPOINT, HttpMethod.POST, null, statement, Object.class); if (response.getStatusCode().series() == Series.SUCCESSFUL) { logger.trace("LRS provider successfully sent to {}, statement: {}", LRSUrl, statement); } else { logger.error("LRS provider failed to send to {}, statement: {}", LRSUrl, statement); logger.error("- Response: {}", response); return false; } return true; }
java
protected void loadConfig() { if (!isEnabled()) { return; } final String urlProp = format(PROPERTY_FORMAT, id, "url"); LRSUrl = propertyResolver.getProperty(urlProp); actorName = propertyResolver.getProperty(format(PROPERTY_FORMAT, id, "actor-name"), actorName); actorEmail = propertyResolver.getProperty( format(PROPERTY_FORMAT, id, "actor-email"), actorEmail); activityId = propertyResolver.getProperty( format(PROPERTY_FORMAT, id, "activity-id"), activityId); stateId = propertyResolver.getProperty(format(PROPERTY_FORMAT, id, "state-id"), stateId); formEncodeActivityData = propertyResolver.getProperty( format(PROPERTY_FORMAT, id, "form-encode-activity-data"), Boolean.class, formEncodeActivityData); activitiesFormParamName = propertyResolver.getProperty( format(PROPERTY_FORMAT, id, "activity-form-param-name"), activitiesFormParamName); if (StringUtils.isEmpty(LRSUrl)) { logger.error("Disabling TinCan API interface. Property {} not set!", urlProp); enabled = false; return; } // strip trailing '/' if included LRSUrl = LRSUrl.replaceAll("/*$", ""); }
java
protected <T> ResponseEntity<T> sendRequest( String pathFragment, HttpMethod method, List<? extends NameValuePair> getParams, Object postData, Class<T> returnType) { HttpHeaders headers = new HttpHeaders(); headers.add(XAPI_VERSION_HEADER, XAPI_VERSION_VALUE); // make multipart data is handled correctly. if (postData instanceof MultiValueMap) { headers.setContentType(MediaType.MULTIPART_FORM_DATA); } URI fullURI = buildRequestURI(pathFragment, getParams); HttpEntity<?> entity = new HttpEntity<>(postData, headers); ResponseEntity<T> response = restTemplate.exchange(fullURI, method, entity, returnType); return response; }
java
private URI buildRequestURI(String pathFragment, List<? extends NameValuePair> params) { try { String queryString = ""; if (params != null && !params.isEmpty()) { queryString = "?" + URLEncodedUtils.format(params, "UTF-8"); } URI fullURI = new URI(LRSUrl + pathFragment + queryString); return fullURI; } catch (URISyntaxException e) { throw new RuntimeException("Error creating request URI", e); } }
java
@Override protected void bindAggregationSpecificKeyParameters( TypedQuery<PortletExecutionAggregationImpl> query, Set<PortletExecutionAggregationKey> keys) { query.setParameter(this.portletMappingParameter, extractAggregatePortletMappings(keys)); query.setParameter(this.executionTypeParameter, extractExecutionTypes(keys)); }
java
protected EntityManager getTransactionalEntityManager(EntityManagerFactory emf) throws IllegalStateException { Assert.state(emf != null, "No EntityManagerFactory specified"); return EntityManagerFactoryUtils.getTransactionalEntityManager(emf); }
java
protected EntityManagerFactory getEntityManagerFactory(OpenEntityManager openEntityManager) { final CacheKey key = this.createEntityManagerFactoryKey(openEntityManager); EntityManagerFactory emf = this.entityManagerFactories.get(key); if (emf == null) { emf = this.lookupEntityManagerFactory(openEntityManager); this.entityManagerFactories.put(key, emf); } return emf; }
java
protected EntityManagerFactory lookupEntityManagerFactory(OpenEntityManager openEntityManager) { String emfBeanName = openEntityManager.name(); String puName = openEntityManager.unitName(); if (StringUtils.hasLength(emfBeanName)) { return this.applicationContext.getBean(emfBeanName, EntityManagerFactory.class); } else if (!StringUtils.hasLength(puName) && this.applicationContext.containsBean( OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) { return this.applicationContext.getBean( OpenEntityManagerInViewFilter.DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class); } else { // Includes fallback search for single EntityManagerFactory bean by type. return EntityManagerFactoryUtils.findEntityManagerFactory( this.applicationContext, puName); } }
java
@Override public synchronized Object put(Object key, Object value) { ValueWrapper valueWrapper = new ValueWrapper(value); return super.put(key, valueWrapper); }
java
public synchronized Object put(Object key, Object value, long lCacheInterval) { ValueWrapper valueWrapper = new ValueWrapper(value, lCacheInterval); return super.put(key, valueWrapper); }
java
@Override public synchronized Object get(Object key) { ValueWrapper valueWrapper = (ValueWrapper) super.get(key); if (valueWrapper != null) { // Check if value has expired long creationTime = valueWrapper.getCreationTime(); long cacheInterval = valueWrapper.getCacheInterval(); long currentTime = System.currentTimeMillis(); if (cacheInterval >= 0 && creationTime + cacheInterval < currentTime) { remove(key); return null; } return valueWrapper.getValue(); } else return null; }
java
protected void sweepCache() { for (Iterator keyIterator = keySet().iterator(); keyIterator.hasNext(); ) { Object key = keyIterator.next(); ValueWrapper valueWrapper = (ValueWrapper) super.get(key); long creationTime = valueWrapper.getCreationTime(); long cacheInterval = valueWrapper.getCacheInterval(); long currentTime = System.currentTimeMillis(); if (cacheInterval >= 0 && creationTime + cacheInterval < currentTime) { remove(key); } } }
java
private String getInitParameter(String name, String defaultValue) { String value = getInitParameter(name); if (value != null) { return value; } return defaultValue; }
java
private String getMediaType(String contentType) { if (contentType == null) { return null; } String result = contentType.toLowerCase(Locale.ENGLISH); int firstSemiColonIndex = result.indexOf(';'); if (firstSemiColonIndex > -1) { result = result.substring(0, firstSemiColonIndex); } result = result.trim(); return result; }
java
public void endParsing() throws SnowflakeSQLException { if (partialEscapedUnicode.position() > 0) { partialEscapedUnicode.flip(); continueParsingInternal(partialEscapedUnicode, true); partialEscapedUnicode.clear(); } if (state != State.ROW_FINISHED) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "SFResultJsonParser2Failed: Chunk is truncated!"); } currentColumn = 0; state = State.UNINITIALIZED; }
java
public void continueParsing(ByteBuffer in) throws SnowflakeSQLException { if (state == State.UNINITIALIZED) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "Json parser hasn't been initialized!"); } // If stopped during a \\u, continue here if (partialEscapedUnicode.position() > 0) { int lenToCopy = Math.min(12 - partialEscapedUnicode.position(), in.remaining()); if (lenToCopy > partialEscapedUnicode.remaining()) { resizePartialEscapedUnicode(lenToCopy); } partialEscapedUnicode.put(in.array(), in.arrayOffset() + in.position(), lenToCopy); in.position(in.position() + lenToCopy); if (partialEscapedUnicode.position() < 12) { // Not enough data to parse escaped unicode return; } ByteBuffer toBeParsed = partialEscapedUnicode.duplicate(); toBeParsed.flip(); continueParsingInternal(toBeParsed, false); partialEscapedUnicode.clear(); } continueParsingInternal(in, false); }
java
public static void cancel(StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpPost httpRequest = null; AssertUtil.assertTrue(stmtInput.serverUrl != null, "Missing server url for statement execution"); AssertUtil.assertTrue(stmtInput.sql != null, "Missing sql for statement execution"); AssertUtil.assertTrue(stmtInput.mediaType != null, "Missing media type for statement execution"); AssertUtil.assertTrue(stmtInput.requestId != null, "Missing request id for statement execution"); AssertUtil.assertTrue(stmtInput.sessionToken != null, "Missing session token for statement execution"); try { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); logger.debug("Aborting query: {}", stmtInput.sql); uriBuilder.setPath(SF_PATH_ABORT_REQUEST_V1); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); httpRequest = new HttpPost(uriBuilder.build()); /* * The JSON input has two fields: sqlText and requestId */ Map sqlJsonBody = new HashMap<String, Object>(); sqlJsonBody.put("sqlText", stmtInput.sql); sqlJsonBody.put("requestId", stmtInput.requestId); String json = mapper.writeValueAsString(sqlJsonBody); logger.debug("JSON for cancel request: {}", json); StringEntity input = new StringEntity(json, Charset.forName("UTF-8")); input.setContentType("application/json"); httpRequest.setEntity(input); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); setServiceNameHeader(stmtInput, httpRequest); String jsonString = HttpUtil.executeRequest(httpRequest, SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS, 0, null); // trace the response if requested logger.debug("Json response: {}", jsonString); JsonNode rootNode = null; rootNode = mapper.readTree(jsonString); // raise server side error as an exception if any SnowflakeUtil.checkErrorAndThrowException(rootNode); } catch (URISyntaxException | IOException ex) { logger.error( "Exception encountered when canceling " + httpRequest, ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } }
java
static public SFStatementType checkStageManageCommand(String sql) { if (sql == null) { return null; } String trimmedSql = sql.trim(); // skip commenting prefixed with // while (trimmedSql.startsWith("//")) { logger.debug("skipping // comments in: \n{}", trimmedSql); if (trimmedSql.indexOf('\n') > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf('\n')); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug("New sql after skipping // comments: \n{}", trimmedSql); } // skip commenting enclosed with /* */ while (trimmedSql.startsWith("/*")) { logger.debug("skipping /* */ comments in: \n{}", trimmedSql); if (trimmedSql.indexOf("*/") > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf("*/") + 2); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug("New sql after skipping /* */ comments: \n{}", trimmedSql); } trimmedSql = trimmedSql.toLowerCase(); if (trimmedSql.startsWith("put ")) { return SFStatementType.PUT; } else if (trimmedSql.startsWith("get ")) { return SFStatementType.GET; } else if (trimmedSql.startsWith("ls ") || trimmedSql.startsWith("list ")) { return SFStatementType.LIST; } else if (trimmedSql.startsWith("rm ") || trimmedSql.startsWith("remove ")) { return SFStatementType.REMOVE; } else { return null; } }
java
public void flush() { if (!enabled) { return; } if (!queue.isEmpty()) { // start a new thread to upload without blocking the current thread Runnable runUpload = new TelemetryUploader(this, exportQueueToString()); uploader.execute(runUpload); } }
java
public String exportQueueToString() { JSONArray logs = new JSONArray(); while (!queue.isEmpty()) { logs.add(queue.poll()); } return SecretDetector.maskAWSSecret(logs.toString()); }
java
public void logHttpRequestTelemetryEvent( String eventName, HttpRequestBase request, int injectSocketTimeout, AtomicBoolean canceling, boolean withoutCookies, boolean includeRetryParameters, boolean includeRequestGuid, CloseableHttpResponse response, final Exception savedEx, String breakRetryReason, long retryTimeout, int retryCount, String sqlState, int errorCode) { if (enabled) { TelemetryEvent.LogBuilder logBuilder = new TelemetryEvent.LogBuilder(); JSONObject value = new JSONObject(); value.put("request", request.toString()); value.put("retryTimeout", retryTimeout); value.put("injectSocketTimeout", injectSocketTimeout); value.put("canceling", canceling == null ? "null" : canceling.get()); value.put("withoutCookies", withoutCookies); value.put("includeRetryParameters", includeRetryParameters); value.put("includeRequestGuid", includeRequestGuid); value.put("breakRetryReason", breakRetryReason); value.put("retryTimeout", retryTimeout); value.put("retryCount", retryCount); value.put("sqlState", sqlState); value.put("errorCode", errorCode); int responseStatusCode = -1; if (response != null) { value.put("response", response.toString()); value.put("responseStatusLine", response.getStatusLine().toString()); if (response.getStatusLine() != null) { responseStatusCode = response.getStatusLine().getStatusCode(); value.put("responseStatusCode", responseStatusCode); } } else { value.put("response", null); } if (savedEx != null) { value.put("exceptionMessage", savedEx.getLocalizedMessage()); StringWriter sw = new StringWriter(); savedEx.printStackTrace(new PrintWriter(sw)); value.put("exceptionStackTrace", sw.toString()); } TelemetryEvent log = logBuilder .withName(eventName) .withValue(value) .withTag("sqlState", sqlState) .withTag("errorCode", errorCode) .withTag("responseStatusCode", responseStatusCode) .build(); this.add(log); } }
java
public final Object getCell(int rowIdx, int colIdx) { if (resultData != null) { return extractCell(resultData, rowIdx, colIdx); } return data.get(colCount * rowIdx + colIdx); }
java
public final void ensureRowsComplete() throws SnowflakeSQLException { // Check that all the rows have been decoded, raise an error if not if (rowCount != currentRow) { throw new SnowflakeSQLException( SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR .getMessageCode(), "Exception: expected " + rowCount + " rows and received " + currentRow); } }
java
static CloseableHttpClient buildHttpClient( boolean insecureMode, File ocspCacheFile, boolean useOcspCacheServer) { // set timeout so that we don't wait forever. // Setup the default configuration for all requests on this client DefaultRequestConfig = RequestConfig.custom() .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT) .setSocketTimeout(DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT) .build(); TrustManager[] trustManagers = null; if (!insecureMode) { // A custom TrustManager is required only if insecureMode is disabled, // which is by default in the production. insecureMode can be enabled // 1) OCSP service is down for reasons, 2) PowerMock test tht doesn't // care OCSP checks. TrustManager[] tm = { new SFTrustManager(ocspCacheFile, useOcspCacheServer)}; trustManagers = tm; } try { Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", new SFSSLConnectionSocketFactory(trustManagers, socksProxyDisabled)) .register("http", new SFConnectionSocketFactory()) .build(); // Build a connection manager with enough connections connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); if (useProxy) { // use the custom proxy properties HttpHost proxy = new HttpHost(proxyHost, proxyPort); Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); AuthScope authScope = new AuthScope(proxyHost, proxyPort); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner( proxyHost, proxyPort, nonProxyHosts ); httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(DefaultRequestConfig) .setConnectionManager(connectionManager) // Support JVM proxy settings .useSystemProperties() .setRedirectStrategy(new DefaultRedirectStrategy()) .setUserAgent("-") // needed for Okta .disableCookieManagement() // SNOW-39748 .setProxy(proxy) .setDefaultCredentialsProvider(credentialsProvider) .setRoutePlanner(sdkProxyRoutePlanner) .build(); } else { httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(DefaultRequestConfig) .setConnectionManager(connectionManager) // Support JVM proxy settings .useSystemProperties() .setRedirectStrategy(new DefaultRedirectStrategy()) .setUserAgent("-") // needed for Okta .disableCookieManagement() // SNOW-39748 .build(); } return httpClient; } catch (NoSuchAlgorithmException | KeyManagementException ex) { throw new SSLInitializationException(ex.getMessage(), ex); } }
java
public static CloseableHttpClient initHttpClient(boolean insecureMode, File ocspCacheFile) { if (httpClient == null) { synchronized (HttpUtil.class) { if (httpClient == null) { httpClient = buildHttpClient( insecureMode, ocspCacheFile, enableOcspResponseCacheServer()); } } } return httpClient; }
java
public static RequestConfig getDefaultRequestConfigWithSocketTimeout(int soTimeoutMs, boolean withoutCookies) { getHttpClient(); final String cookieSpec = withoutCookies ? IGNORE_COOKIES : DEFAULT; return RequestConfig.copy(DefaultRequestConfig) .setSocketTimeout(soTimeoutMs) .setCookieSpec(cookieSpec) .build(); }
java
static String executeRequestWithoutCookies(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequestInternal( httpRequest, retryTimeout, injectSocketTimeout, canceling, true, false, true); }
java
public static String executeRequest(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequest( httpRequest, retryTimeout, injectSocketTimeout, canceling, false); }
java
public static void configureCustomProxyProperties( Map<SFSessionProperty, Object> connectionPropertiesMap) { if (connectionPropertiesMap.containsKey(SFSessionProperty.USE_PROXY)) { useProxy = (boolean) connectionPropertiesMap.get( SFSessionProperty.USE_PROXY); } if (useProxy) { proxyHost = (String) connectionPropertiesMap.get(SFSessionProperty.PROXY_HOST); proxyPort = Integer.parseInt( connectionPropertiesMap.get(SFSessionProperty.PROXY_PORT).toString()); proxyUser = (String) connectionPropertiesMap.get(SFSessionProperty.PROXY_USER); proxyPassword = (String) connectionPropertiesMap.get(SFSessionProperty.PROXY_PASSWORD); nonProxyHosts = (String) connectionPropertiesMap.get(SFSessionProperty.NON_PROXY_HOSTS); } }
java
static private void checkErrorAndThrowExceptionSub( JsonNode rootNode, boolean raiseReauthenticateError) throws SnowflakeSQLException { // no need to throw exception if success if (rootNode.path("success").asBoolean()) { return; } String errorMessage; String sqlState; int errorCode; String queryId = "unknown"; // if we have sqlstate in data, it's a sql error if (!rootNode.path("data").path("sqlState").isMissingNode()) { sqlState = rootNode.path("data").path("sqlState").asText(); errorCode = rootNode.path("data").path("errorCode").asInt(); queryId = rootNode.path("data").path("queryId").asText(); errorMessage = rootNode.path("message").asText(); } else { sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state // check if there is an error code in the envelope if (!rootNode.path("code").isMissingNode()) { errorCode = rootNode.path("code").asInt(); errorMessage = rootNode.path("message").asText(); } else { errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode(); errorMessage = "no_error_code_from_server"; try { PrintWriter writer = new PrintWriter("output.json", "UTF-8"); writer.print(rootNode.toString()); } catch (Exception ex) { logger.debug("{}", ex); } } } if (raiseReauthenticateError) { switch (errorCode) { case ID_TOKEN_EXPIRED_GS_CODE: case SESSION_NOT_EXIST_GS_CODE: case MASTER_TOKEN_NOTFOUND: case MASTER_EXPIRED_GS_CODE: case MASTER_TOKEN_INVALID_GS_CODE: throw new SnowflakeReauthenticationRequest( queryId, errorMessage, sqlState, errorCode); } } throw new SnowflakeSQLException(queryId, errorMessage, sqlState, errorCode); }
java
static void assertTrue(boolean condition, String internalErrorMesg) throws SFException { if (!condition) { throw new SFException(ErrorCode.INTERNAL_ERROR, internalErrorMesg); } }
java
public static MatDesc parse(String matdesc) { if (matdesc == null) { return null; } try { JsonNode jsonNode = mapper.readTree(matdesc); JsonNode queryIdNode = jsonNode.path(QUERY_ID); if (queryIdNode.isMissingNode() || queryIdNode.isNull()) { return null; } JsonNode smkIdNode = jsonNode.path(SMK_ID); if (smkIdNode.isMissingNode() || smkIdNode.isNull()) { return null; } String queryId = queryIdNode.asText(); long smkId = smkIdNode.asLong(); JsonNode keySizeNode = jsonNode.path(KEY_SIZE); if (!keySizeNode.isMissingNode() && !keySizeNode.isNull()) { return new MatDesc(smkId, queryId, keySizeNode.asInt()); } return new MatDesc(smkId, queryId); } catch (Exception ex) { return null; } }
java
private SFPair<String, String> applySessionContext(String catalog, String schemaPattern) { if (catalog == null && metadataRequestUseConnectionCtx) { catalog = session.getDatabase(); if (schemaPattern == null) { schemaPattern = session.getSchema(); } } return SFPair.of(catalog, schemaPattern); }
java
private short getForeignKeyConstraintProperty( String property_name, String property) { short result = 0; switch (property_name) { case "update": case "delete": switch (property) { case "NO ACTION": result = importedKeyNoAction; break; case "CASCADE": result = importedKeyCascade; break; case "SET NULL": result = importedKeySetNull; break; case "SET DEFAULT": result = importedKeySetDefault; break; case "RESTRICT": result = importedKeyRestrict; break; } case "deferrability": switch (property) { case "INITIALLY DEFERRED": result = importedKeyInitiallyDeferred; break; case "INITIALLY IMMEDIATE": result = importedKeyInitiallyImmediate; break; case "NOT DEFERRABLE": result = importedKeyNotDeferrable; break; } } return result; }
java
private ResultSet executeAndReturnEmptyResultIfNotFound(Statement statement, String sql, DBMetadataResultSetMetadata metadataType) throws SQLException { ResultSet resultSet; try { resultSet = statement.executeQuery(sql); } catch (SnowflakeSQLException e) { if (e.getSQLState().equals(SqlState.NO_DATA) || e.getSQLState().equals(SqlState.BASE_TABLE_OR_VIEW_NOT_FOUND)) { return SnowflakeDatabaseMetaDataResultSet.getEmptyResultSet(metadataType, statement); } else { throw e; } } return resultSet; }
java
static private ClientAuthnDTO.AuthenticatorType getAuthenticator( LoginInput loginInput) { if (loginInput.getAuthenticator() != null) { if (loginInput.getAuthenticator().equalsIgnoreCase( ClientAuthnDTO.AuthenticatorType.EXTERNALBROWSER.name())) { // SAML 2.0 compliant service/application return ClientAuthnDTO.AuthenticatorType.EXTERNALBROWSER; } else if (loginInput.getAuthenticator().equalsIgnoreCase( ClientAuthnDTO.AuthenticatorType.OAUTH.name())) { // OAuth Authentication return ClientAuthnDTO.AuthenticatorType.OAUTH; } else if (loginInput.getAuthenticator().equalsIgnoreCase( ClientAuthnDTO.AuthenticatorType.SNOWFLAKE_JWT.name())) { return ClientAuthnDTO.AuthenticatorType.SNOWFLAKE_JWT; } else if (!loginInput.getAuthenticator().equalsIgnoreCase( ClientAuthnDTO.AuthenticatorType.SNOWFLAKE.name())) { // OKTA authenticator v1. This will be deprecated once externalbrowser // is in production. return ClientAuthnDTO.AuthenticatorType.OKTA; } } // authenticator is null, then jdbc will decide authenticator depends on // if privateKey is specified or not. If yes, authenticator type will be // SNOWFLAKE_JWT, otherwise it will use SNOWFLAKE. return loginInput.getPrivateKey() != null ? ClientAuthnDTO.AuthenticatorType.SNOWFLAKE_JWT : ClientAuthnDTO.AuthenticatorType.SNOWFLAKE; }
java
static public LoginOutput openSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { AssertUtil.assertTrue(loginInput.getServerUrl() != null, "missing server URL for opening session"); AssertUtil.assertTrue(loginInput.getAppId() != null, "missing app id for opening session"); AssertUtil.assertTrue(loginInput.getLoginTimeout() >= 0, "negative login timeout for opening session"); final ClientAuthnDTO.AuthenticatorType authenticator = getAuthenticator( loginInput); if (!authenticator.equals(ClientAuthnDTO.AuthenticatorType.OAUTH)) { // OAuth does not require a username AssertUtil.assertTrue(loginInput.getUserName() != null, "missing user name for opening session"); } if (authenticator.equals(ClientAuthnDTO.AuthenticatorType.EXTERNALBROWSER)) { // force to set the flag. loginInput.sessionParameters.put(CLIENT_STORE_TEMPORARY_CREDENTIAL, true); } else { // TODO: patch for now. We should update mergeProperteis // to normalize all parameters using STRING_PARAMS, INT_PARAMS and // BOOLEAN_PARAMS. Object value = loginInput.sessionParameters.get( CLIENT_STORE_TEMPORARY_CREDENTIAL); if (value != null) { loginInput.sessionParameters.put( CLIENT_STORE_TEMPORARY_CREDENTIAL, asBoolean(value)); } } boolean isClientStoreTemporaryCredential = asBoolean( loginInput.sessionParameters.get(CLIENT_STORE_TEMPORARY_CREDENTIAL)); LoginOutput loginOutput; if (isClientStoreTemporaryCredential && (loginOutput = readTemporaryCredential(loginInput)) != null) { return loginOutput; } return newSession(loginInput); }
java
static public LoginOutput issueSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { return tokenRequest(loginInput, TokenRequestType.ISSUE); }
java
static public void closeSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { logger.debug(" public void close() throws SFException"); // assert the following inputs are valid AssertUtil.assertTrue(loginInput.getServerUrl() != null, "missing server URL for closing session"); AssertUtil.assertTrue(loginInput.getSessionToken() != null, "missing session token for closing session"); AssertUtil.assertTrue(loginInput.getLoginTimeout() >= 0, "missing login timeout for closing session"); HttpPost postRequest = null; try { URIBuilder uriBuilder; uriBuilder = new URIBuilder(loginInput.getServerUrl()); uriBuilder.addParameter(SF_QUERY_SESSION_DELETE, "true"); uriBuilder.addParameter(SFSession.SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); uriBuilder.setPath(SF_PATH_SESSION); postRequest = new HttpPost(uriBuilder.build()); postRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + loginInput.getSessionToken() + "\""); setServiceNameHeader(loginInput, postRequest); String theString = HttpUtil.executeRequest(postRequest, loginInput.getLoginTimeout(), 0, null); JsonNode rootNode; logger.debug( "connection close response: {}", theString); rootNode = mapper.readTree(theString); SnowflakeUtil.checkErrorAndThrowException(rootNode); } catch (URISyntaxException ex) { throw new RuntimeException("unexpected URI syntax exception", ex); } catch (IOException ex) { logger.error("unexpected IO exception for: " + postRequest, ex); } catch (SnowflakeSQLException ex) { // ignore session expiration exception if (ex.getErrorCode() != Constants.SESSION_EXPIRED_GS_CODE) { throw ex; } } }
java
private static String federatedFlowStep3(LoginInput loginInput, String tokenUrl) throws SnowflakeSQLException { String oneTimeToken = ""; try { URL url = new URL(tokenUrl); URI tokenUri = url.toURI(); final HttpPost postRequest = new HttpPost(tokenUri); StringEntity params = new StringEntity("{\"username\":\"" + loginInput.getUserName() + "\",\"password\":\"" + loginInput.getPassword() + "\"}"); postRequest.setEntity(params); HeaderGroup headers = new HeaderGroup(); headers.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "application/json")); headers.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); postRequest.setHeaders(headers.getAllHeaders()); final String idpResponse = HttpUtil.executeRequestWithoutCookies(postRequest, loginInput.getLoginTimeout(), 0, null); logger.debug("user is authenticated against {}.", loginInput.getAuthenticator()); // session token is in the data field of the returned json response final JsonNode jsonNode = mapper.readTree(idpResponse); oneTimeToken = jsonNode.get("cookieToken").asText(); } catch (IOException | URISyntaxException ex) { handleFederatedFlowError(loginInput, ex); } return oneTimeToken; }
java
private static JsonNode federatedFlowStep1(LoginInput loginInput) throws SnowflakeSQLException { JsonNode dataNode = null; try { URIBuilder fedUriBuilder = new URIBuilder(loginInput.getServerUrl()); fedUriBuilder.setPath(SF_PATH_AUTHENTICATOR_REQUEST); URI fedUrlUri = fedUriBuilder.build(); Map<String, Object> data = new HashMap<>(); data.put(ClientAuthnParameter.ACCOUNT_NAME.name(), loginInput.getAccountName()); data.put(ClientAuthnParameter.AUTHENTICATOR.name(), loginInput.getAuthenticator()); data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId()); data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(), loginInput.getAppVersion()); ClientAuthnDTO authnData = new ClientAuthnDTO(); authnData.setData(data); String json = mapper.writeValueAsString(authnData); // attach the login info json body to the post request StringEntity input = new StringEntity(json, Charset.forName("UTF-8")); input.setContentType("application/json"); HttpPost postRequest = new HttpPost(fedUrlUri); postRequest.setEntity(input); postRequest.addHeader("accept", "application/json"); final String gsResponse = HttpUtil.executeRequest(postRequest, loginInput.getLoginTimeout(), 0, null); logger.debug("authenticator-request response: {}", gsResponse); JsonNode jsonNode = mapper.readTree(gsResponse); // check the success field first if (!jsonNode.path("success").asBoolean()) { logger.debug("response = {}", gsResponse); String errorCode = jsonNode.path("code").asText(); throw new SnowflakeSQLException( SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION, ErrorCode.CONNECTION_ERROR.getMessageCode(), errorCode, jsonNode.path("message").asText()); } // session token is in the data field of the returned json response dataNode = jsonNode.path("data"); } catch (IOException | URISyntaxException ex) { handleFederatedFlowError(loginInput, ex); } return dataNode; }
java
private static void handleFederatedFlowError(LoginInput loginInput, Exception ex) throws SnowflakeSQLException { if (ex instanceof IOException) { logger.error("IOException when authenticating with " + loginInput.getAuthenticator(), ex); throw new SnowflakeSQLException(ex, SqlState.IO_ERROR, ErrorCode.NETWORK_ERROR.getMessageCode(), "Exception encountered when opening connection: " + ex.getMessage()); } logger.error("Exception when authenticating with " + loginInput.getAuthenticator(), ex); throw new SnowflakeSQLException(ex, SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION, ErrorCode.CONNECTION_ERROR.getMessageCode(), ErrorCode.CONNECTION_ERROR.getMessageCode(), ex.getMessage()); }
java
static private String getSamlResponseUsingOkta(LoginInput loginInput) throws SnowflakeSQLException { JsonNode dataNode = federatedFlowStep1(loginInput); String tokenUrl = dataNode.path("tokenUrl").asText(); String ssoUrl = dataNode.path("ssoUrl").asText(); federatedFlowStep2(loginInput, tokenUrl, ssoUrl); final String oneTimeToken = federatedFlowStep3(loginInput, tokenUrl); final String responseHtml = federatedFlowStep4( loginInput, ssoUrl, oneTimeToken); return responseHtml; }
java
static boolean isPrefixEqual(String aUrlStr, String bUrlStr) throws MalformedURLException { URL aUrl = new URL(aUrlStr); URL bUrl = new URL(bUrlStr); int aPort = aUrl.getPort(); int bPort = bUrl.getPort(); if (aPort == -1 && "https".equals(aUrl.getProtocol())) { // default port number for HTTPS aPort = 443; } if (bPort == -1 && "https".equals(bUrl.getProtocol())) { // default port number for HTTPS bPort = 443; } // no default port number for HTTP is supported. return aUrl.getHost().equalsIgnoreCase(bUrl.getHost()) && aUrl.getProtocol().equalsIgnoreCase(bUrl.getProtocol()) && aPort == bPort; }
java
static private String getPostBackUrlFromHTML(String html) { Document doc = Jsoup.parse(html); Elements e1 = doc.getElementsByTag("body"); Elements e2 = e1.get(0).getElementsByTag("form"); String postBackUrl = e2.first().attr("action"); return postBackUrl; }
java
public static Map<String, Object> getCommonParams(JsonNode paramsNode) { Map<String, Object> parameters = new HashMap<>(); for (JsonNode child : paramsNode) { // If there isn't a name then the response from GS must be erroneous. if (!child.hasNonNull("name")) { logger.error("Common Parameter JsonNode encountered with " + "no parameter name!"); continue; } // Look up the parameter based on the "name" attribute of the node. String paramName = child.path("name").asText(); // What type of value is it and what's the value? if (!child.hasNonNull("value")) { logger.debug("No value found for Common Parameter {}", child.path("name").asText()); continue; } if (STRING_PARAMS.contains(paramName.toUpperCase())) { parameters.put(paramName, child.path("value").asText()); } else if (INT_PARAMS.contains(paramName.toUpperCase())) { parameters.put(paramName, child.path("value").asInt()); } else if (BOOLEAN_PARAMS.contains(paramName.toUpperCase())) { parameters.put(paramName, child.path("value").asBoolean()); } else { logger.debug("Unknown Common Parameter: {}", paramName); } logger.debug("Parameter {}: {}", paramName, child.path("value").asText()); } return parameters; }
java
protected ServerSocket getServerSocket() throws SFException { try { return new ServerSocket( 0, // free port 0, // default number of connections InetAddress.getByName("localhost")); } catch (IOException ex) { throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage()); } }
java
private String getSSOUrl(int port) throws SFException, SnowflakeSQLException { try { String serverUrl = loginInput.getServerUrl(); String authenticator = loginInput.getAuthenticator(); URIBuilder fedUriBuilder = new URIBuilder(serverUrl); fedUriBuilder.setPath(SessionUtil.SF_PATH_AUTHENTICATOR_REQUEST); URI fedUrlUri = fedUriBuilder.build(); HttpPost postRequest = this.handlers.build(fedUrlUri); ClientAuthnDTO authnData = new ClientAuthnDTO(); Map<String, Object> data = new HashMap<>(); data.put(ClientAuthnParameter.AUTHENTICATOR.name(), authenticator); data.put(ClientAuthnParameter.ACCOUNT_NAME.name(), loginInput.getAccountName()); data.put(ClientAuthnParameter.LOGIN_NAME.name(), loginInput.getUserName()); data.put(ClientAuthnParameter.BROWSER_MODE_REDIRECT_PORT.name(), Integer.toString(port)); data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId()); data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(), loginInput.getAppVersion()); authnData.setData(data); String json = mapper.writeValueAsString(authnData); // attach the login info json body to the post request StringEntity input = new StringEntity(json, Charset.forName("UTF-8")); input.setContentType("application/json"); postRequest.setEntity(input); postRequest.addHeader("accept", "application/json"); String theString = HttpUtil.executeRequest(postRequest, loginInput.getLoginTimeout(), 0, null); logger.debug("authenticator-request response: {}", theString); // general method, same as with data binding JsonNode jsonNode = mapper.readTree(theString); // check the success field first if (!jsonNode.path("success").asBoolean()) { logger.debug("response = {}", theString); String errorCode = jsonNode.path("code").asText(); throw new SnowflakeSQLException( SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION, new Integer(errorCode), jsonNode.path("message").asText()); } JsonNode dataNode = jsonNode.path("data"); // session token is in the data field of the returned json response this.proofKey = dataNode.path("proofKey").asText(); return dataNode.path("ssoUrl").asText(); } catch (IOException | URISyntaxException ex) { throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage()); } }
java
private void processSamlToken(String[] rets, Socket socket) throws IOException, SFException { String targetLine = null; String userAgent = null; boolean isPost = false; for (String line : rets) { if (line.length() > PREFIX_GET.length() && line.substring(0, PREFIX_GET.length()).equalsIgnoreCase(PREFIX_GET)) { targetLine = line; } else if (line.length() > PREFIX_POST.length() && line.substring(0, PREFIX_POST.length()).equalsIgnoreCase(PREFIX_POST)) { targetLine = rets[rets.length - 1]; isPost = true; } else if (line.length() > PREFIX_USER_AGENT.length() && line.substring(0, PREFIX_USER_AGENT.length()).equalsIgnoreCase(PREFIX_USER_AGENT)) { userAgent = line; } } if (targetLine == null) { throw new SFException(ErrorCode.NETWORK_ERROR, "Invalid HTTP request. No token is given from the browser."); } if (userAgent != null) { logger.debug("{}", userAgent); } try { // attempt to get JSON response extractJsonTokenFromPostRequest(targetLine); } catch (IOException ex) { String parameters = isPost ? extractTokenFromPostRequest(targetLine) : extractTokenFromGetRequest(targetLine); try { URI inputParameter = new URI(parameters); for (NameValuePair urlParam : URLEncodedUtils.parse( inputParameter, UTF8_CHARSET)) { if ("token".equals(urlParam.getName())) { this.token = urlParam.getValue(); break; } } } catch (URISyntaxException ex0) { throw new SFException(ErrorCode.NETWORK_ERROR, String.format( "Invalid HTTP request. No token is given from the browser. %s, err: %s", targetLine, ex0)); } } if (this.token == null) { throw new SFException(ErrorCode.NETWORK_ERROR, String.format( "Invalid HTTP request. No token is given from the browser: %s", targetLine)); } returnToBrowser(socket); }
java
private void returnToBrowser(Socket socket) throws IOException { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); List<String> content = new ArrayList<>(); content.add("HTTP/1.0 200 OK"); content.add("Content-Type: text/html"); String responseText; if (this.origin != null) { content.add( String.format("Access-Control-Allow-Origin: %s", this.origin)); content.add("Vary: Accept-Encoding, Origin"); Map<String, Object> data = new HashMap<>(); data.put("consent", this.consentCacheIdToken); responseText = mapper.writeValueAsString(data); } else { responseText = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/>" + "<title>SAML Response for Snowflake</title></head>" + "<body>Your identity was confirmed and propagated to " + "Snowflake JDBC driver. You can close this window now and go back " + "where you started from.</body></html>"; } content.add(String.format("Content-Length: %s", responseText.length())); content.add(""); content.add(responseText); for (int i = 0; i < content.size(); ++i) { if (i > 0) { out.print("\r\n"); } out.print(content.get(i)); } out.flush(); }
java
public static TelemetryData buildJobData(String queryId, TelemetryField field, long value) { ObjectNode obj = mapper.createObjectNode(); obj.put(TYPE, field.toString()); obj.put(QUERY_ID, queryId); obj.put(VALUE, value); return new TelemetryData(obj, System.currentTimeMillis()); }
java
@Override public void download(SFSession connection, String command, String localLocation, String destFileName, int parallelism, String remoteStorageLocation, String stageFilePath, String stageRegion) throws SnowflakeSQLException { TransferManager tx = null; int retryCount = 0; do { try { File localFile = new File(localLocation + localFileSep + destFileName); logger.debug("Creating executor service for transfer" + "manager with {} threads", parallelism); // download file from s3 tx = new TransferManager(amazonClient, SnowflakeUtil.createDefaultExecutorService( "s3-transfer-manager-downloader-", parallelism)); Download myDownload = tx.download(remoteStorageLocation, stageFilePath, localFile); // Pull object metadata from S3 ObjectMetadata meta = amazonClient.getObjectMetadata(remoteStorageLocation, stageFilePath); Map<String, String> metaMap = meta.getUserMetadata(); String key = metaMap.get(AMZ_KEY); String iv = metaMap.get(AMZ_IV); myDownload.waitForCompletion(); if (this.isEncrypting() && this.getEncryptionKeySize() < 256) { if (key == null || iv == null) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "File metadata incomplete"); } // Decrypt file try { EncryptionProvider.decrypt(localFile, key, iv, this.encMat); } catch (Exception ex) { logger.error("Error decrypting file", ex); throw ex; } } return; } catch (Exception ex) { handleS3Exception(ex, ++retryCount, "download", connection, command, this); } finally { if (tx != null) { tx.shutdownNow(false); } } } while (retryCount <= getMaxRetries()); throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "Unexpected: download unsuccessful without exception!"); }
java
static void resetOCSPResponseCacherServerURL(String ocspCacheServerUrl) { if (ocspCacheServerUrl == null || SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null) { return; } SF_OCSP_RESPONSE_CACHE_SERVER_URL = ocspCacheServerUrl; if (!SF_OCSP_RESPONSE_CACHE_SERVER_URL.startsWith(DEFAULT_OCSP_CACHE_HOST)) { try { URL url = new URL(SF_OCSP_RESPONSE_CACHE_SERVER_URL); if (url.getPort() > 0) { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s:%d/retry/%s", url.getProtocol(), url.getHost(), url.getPort(), "%s/%s"); } else { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s/retry/%s", url.getProtocol(), url.getHost(), "%s/%s"); } } catch (IOException e) { throw new RuntimeException( String.format( "Failed to parse SF_OCSP_RESPONSE_CACHE_SERVER_URL: %s", SF_OCSP_RESPONSE_CACHE_SERVER_URL)); } } }
java
private X509TrustManager getTrustManager(String algorithm) { try { TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm); factory.init((KeyStore) null); X509TrustManager ret = null; for (TrustManager tm : factory.getTrustManagers()) { // Multiple TrustManager may be attached. We just need X509 Trust // Manager here. if (tm instanceof X509TrustManager) { ret = (X509TrustManager) tm; break; } } if (ret == null) { return null; } synchronized (ROOT_CA_LOCK) { // cache root CA certificates for later use. if (ROOT_CA.size() == 0) { for (X509Certificate cert : ret.getAcceptedIssuers()) { Certificate bcCert = Certificate.getInstance(cert.getEncoded()); ROOT_CA.put(bcCert.getSubject().hashCode(), bcCert); } } } return ret; } catch (NoSuchAlgorithmException | KeyStoreException | CertificateEncodingException ex) { throw new SSLInitializationException(ex.getMessage(), ex); } }
java
void validateRevocationStatus(X509Certificate[] chain, String peerHost) throws CertificateException { final List<Certificate> bcChain = convertToBouncyCastleCertificate(chain); final List<SFPair<Certificate, Certificate>> pairIssuerSubjectList = getPairIssuerSubject(bcChain); if (peerHost.startsWith("ocspssd")) { return; } if (ocspCacheServer.new_endpoint_enabled) { ocspCacheServer.resetOCSPResponseCacheServer(peerHost); } synchronized (OCSP_RESPONSE_CACHE_LOCK) { boolean isCached = isCached(pairIssuerSubjectList); if (this.useOcspResponseCacheServer && !isCached) { if (!ocspCacheServer.new_endpoint_enabled) { LOGGER.debug( "Downloading OCSP response cache from the server. URL: {}", SF_OCSP_RESPONSE_CACHE_SERVER_URL); } else { LOGGER.debug( "Downloading OCSP response cache from the server. URL: {}", ocspCacheServer.SF_OCSP_RESPONSE_CACHE_SERVER); } readOcspResponseCacheServer(); // if the cache is downloaded from the server, it should be written // to the file cache at all times. WAS_CACHE_UPDATED = true; } executeRevocationStatusChecks(pairIssuerSubjectList, peerHost); if (WAS_CACHE_UPDATED) { JsonNode input = encodeCacheToJSON(); fileCacheManager.writeCacheFile(input); WAS_CACHE_UPDATED = false; } } }
java
private void executeRevocationStatusChecks( List<SFPair<Certificate, Certificate>> pairIssuerSubjectList, String peerHost) throws CertificateException { long currentTimeSecond = new Date().getTime() / 1000L; try { for (SFPair<Certificate, Certificate> pairIssuerSubject : pairIssuerSubjectList) { executeOneRevoctionStatusCheck(pairIssuerSubject, currentTimeSecond, peerHost); } } catch (IOException ex) { LOGGER.debug("Failed to decode CertID. Ignored."); } }
java
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key) { try { DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash); ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, snumber); return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()); } catch (Exception ex) { LOGGER.debug("Failed to encode cache key to base64 encoded cert id"); } return null; }
java
private boolean isCached(List<SFPair<Certificate, Certificate>> pairIssuerSubjectList) { long currentTimeSecond = new Date().getTime() / 1000L; boolean isCached = true; try { for (SFPair<Certificate, Certificate> pairIssuerSubject : pairIssuerSubjectList) { OCSPReq req = createRequest(pairIssuerSubject); CertificateID certificateId = req.getRequestList()[0].getCertID(); LOGGER.debug(CertificateIDToString(certificateId)); CertID cid = certificateId.toASN1Primitive(); OcspResponseCacheKey k = new OcspResponseCacheKey( cid.getIssuerNameHash().getEncoded(), cid.getIssuerKeyHash().getEncoded(), cid.getSerialNumber().getValue()); SFPair<Long, String> res = OCSP_RESPONSE_CACHE.get(k); if (res == null) { LOGGER.debug("Not all OCSP responses for the certificate is in the cache."); isCached = false; break; } else if (currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS > res.left) { LOGGER.debug("Cache for CertID expired."); isCached = false; break; } else { try { validateRevocationStatusMain(pairIssuerSubject, res.right); } catch (CertificateException ex) { LOGGER.debug("Cache includes invalid OCSPResponse. " + "Will download the OCSP cache from Snowflake OCSP server"); isCached = false; } } } } catch (IOException ex) { LOGGER.debug("Failed to encode CertID."); } return isCached; }
java
private static String CertificateIDToString(CertificateID certificateID) { return String.format("CertID. NameHash: %s, KeyHash: %s, Serial Number: %s", byteToHexString(certificateID.getIssuerNameHash()), byteToHexString(certificateID.getIssuerKeyHash()), MessageFormat.format("{0,number,#}", certificateID.getSerialNumber())); }
java
private static SFPair<OcspResponseCacheKey, SFPair<Long, String>> decodeCacheFromJSON(Map.Entry<String, JsonNode> elem) throws IOException { long currentTimeSecond = new Date().getTime() / 1000; byte[] certIdDer = Base64.decodeBase64(elem.getKey()); DLSequence rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(certIdDer); ASN1Encodable[] rawCertIdArray = rawCertId.toArray(); byte[] issuerNameHashDer = ((DEROctetString) rawCertIdArray[1]).getEncoded(); byte[] issuerKeyHashDer = ((DEROctetString) rawCertIdArray[2]).getEncoded(); BigInteger serialNumber = ((ASN1Integer) rawCertIdArray[3]).getValue(); OcspResponseCacheKey k = new OcspResponseCacheKey( issuerNameHashDer, issuerKeyHashDer, serialNumber); JsonNode ocspRespBase64 = elem.getValue(); if (!ocspRespBase64.isArray() || ocspRespBase64.size() != 2) { LOGGER.debug("Invalid cache file format."); return null; } long producedAt = ocspRespBase64.get(0).asLong(); String ocspResp = ocspRespBase64.get(1).asText(); if (currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS <= producedAt) { // add cache return SFPair.of(k, SFPair.of(producedAt, ocspResp)); } else { // delete cache return SFPair.of(k, SFPair.of(producedAt, (String) null)); } }
java
private static ObjectNode encodeCacheToJSON() { try { ObjectNode out = OBJECT_MAPPER.createObjectNode(); for (Map.Entry<OcspResponseCacheKey, SFPair<Long, String>> elem : OCSP_RESPONSE_CACHE.entrySet()) { OcspResponseCacheKey key = elem.getKey(); SFPair<Long, String> value0 = elem.getValue(); long currentTimeSecond = value0.left; DigestCalculator digest = new SHA1DigestCalculator(); AlgorithmIdentifier algo = digest.getAlgorithmIdentifier(); ASN1OctetString nameHash = ASN1OctetString.getInstance(key.nameHash); ASN1OctetString keyHash = ASN1OctetString.getInstance(key.keyHash); ASN1Integer serialNumber = new ASN1Integer(key.serialNumber); CertID cid = new CertID(algo, nameHash, keyHash, serialNumber); ArrayNode vout = OBJECT_MAPPER.createArrayNode(); vout.add(currentTimeSecond); vout.add(value0.right); out.set( Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()), vout); } return out; } catch (IOException ex) { LOGGER.debug("Failed to encode ASN1 object."); } return null; }
java
private void validateRevocationStatusMain( SFPair<Certificate, Certificate> pairIssuerSubject, String ocspRespB64) throws CertificateException { try { OCSPResp ocspResp = b64ToOCSPResp(ocspRespB64); Date currentTime = new Date(); BasicOCSPResp basicOcspResp = (BasicOCSPResp) (ocspResp.getResponseObject()); X509CertificateHolder[] attachedCerts = basicOcspResp.getCerts(); X509CertificateHolder signVerifyCert; if (attachedCerts.length > 0) { LOGGER.debug( "Certificate is attached for verification. " + "Verifying it by the issuer certificate."); signVerifyCert = attachedCerts[0]; if (currentTime.after(signVerifyCert.getNotAfter()) || currentTime.before(signVerifyCert.getNotBefore())) { throw new OCSPException(String.format("Cert attached to OCSP Response is invalid." + "Current time - %s" + "Certificate not before time - %s" + "Certificate not after time - %s", currentTime.toString(), signVerifyCert.getNotBefore().toString(), signVerifyCert.getNotAfter().toString())); } verifySignature( new X509CertificateHolder(pairIssuerSubject.left.getEncoded()), signVerifyCert.getSignature(), CONVERTER_X509.getCertificate(signVerifyCert).getTBSCertificate(), signVerifyCert.getSignatureAlgorithm()); LOGGER.debug( "Verifying OCSP signature by the attached certificate public key." ); } else { LOGGER.debug("Certificate is NOT attached for verification. " + "Verifying OCSP signature by the issuer public key."); signVerifyCert = new X509CertificateHolder( pairIssuerSubject.left.getEncoded()); } verifySignature( signVerifyCert, basicOcspResp.getSignature(), basicOcspResp.getTBSResponseData(), basicOcspResp.getSignatureAlgorithmID()); validateBasicOcspResponse(currentTime, basicOcspResp); } catch (IOException | OCSPException ex) { throw new CertificateEncodingException( "Failed to check revocation status.", ex); } }
java
private void validateBasicOcspResponse( Date currentTime, BasicOCSPResp basicOcspResp) throws CertificateEncodingException { for (SingleResp singleResps : basicOcspResp.getResponses()) { Date thisUpdate = singleResps.getThisUpdate(); Date nextUpdate = singleResps.getNextUpdate(); LOGGER.debug("Current Time: {}, This Update: {}, Next Update: {}", currentTime, thisUpdate, nextUpdate); CertificateStatus certStatus = singleResps.getCertStatus(); if (certStatus != CertificateStatus.GOOD) { if (certStatus instanceof RevokedStatus) { RevokedStatus status = (RevokedStatus) certStatus; int reason; try { reason = status.getRevocationReason(); } catch (IllegalStateException ex) { reason = -1; } Date revocationTime = status.getRevocationTime(); throw new CertificateEncodingException( String.format( "The certificate has been revoked. Reason: %d, Time: %s", reason, DATE_FORMAT_UTC.format(revocationTime))); } else { // Unknown status throw new CertificateEncodingException( "Failed to validate the certificate for UNKNOWN reason."); } } if (!isValidityRange(currentTime, thisUpdate, nextUpdate)) { throw new CertificateEncodingException( String.format( "The validity is out of range: " + "Current Time: %s, This Update: %s, Next Update: %s", DATE_FORMAT_UTC.format(currentTime), DATE_FORMAT_UTC.format(thisUpdate), DATE_FORMAT_UTC.format(nextUpdate))); } } LOGGER.debug("OK. Verified the certificate revocation status."); }
java
private static void verifySignature( X509CertificateHolder cert, byte[] sig, byte[] data, AlgorithmIdentifier idf) throws CertificateException { try { String algorithm = SIGNATURE_OID_TO_STRING.get(idf.getAlgorithm()); if (algorithm == null) { throw new NoSuchAlgorithmException( String.format("Unsupported signature OID. OID: %s", idf)); } Signature signer = Signature.getInstance( algorithm, BouncyCastleProvider.PROVIDER_NAME); X509Certificate c = CONVERTER_X509.getCertificate(cert); signer.initVerify(c.getPublicKey()); signer.update(data); if (!signer.verify(sig)) { throw new CertificateEncodingException( String.format("Failed to verify the signature. Potentially the " + "data was not generated by by the cert, %s", cert.getSubject())); } } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException ex) { throw new CertificateEncodingException( "Failed to verify the signature.", ex); } }
java
private static String byteToHexString(byte[] bytes) { final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); }
java
private OCSPReq createRequest( SFPair<Certificate, Certificate> pairIssuerSubject) { Certificate issuer = pairIssuerSubject.left; Certificate subject = pairIssuerSubject.right; OCSPReqBuilder gen = new OCSPReqBuilder(); try { DigestCalculator digest = new SHA1DigestCalculator(); X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded()); CertificateID certId = new CertificateID( digest, certHolder, subject.getSerialNumber().getValue()); gen.addRequest(certId); return gen.build(); } catch (OCSPException | IOException ex) { throw new RuntimeException("Failed to build a OCSPReq."); } }
java
private List<Certificate> convertToBouncyCastleCertificate( X509Certificate[] chain) { final List<Certificate> bcChain = new ArrayList<>(); for (X509Certificate cert : chain) { try { bcChain.add(Certificate.getInstance(cert.getEncoded())); } catch (CertificateEncodingException ex) { throw new RuntimeException("Failed to decode the certificate DER data"); } } return bcChain; }
java
private List<SFPair<Certificate, Certificate>> getPairIssuerSubject( List<Certificate> bcChain) { List<SFPair<Certificate, Certificate>> pairIssuerSubject = new ArrayList<>(); for (int i = 0, len = bcChain.size(); i < len; ++i) { Certificate bcCert = bcChain.get(i); if (bcCert.getIssuer().equals(bcCert.getSubject())) { continue; // skipping ROOT CA } if (i < len - 1) { pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i))); } else { synchronized (ROOT_CA_LOCK) { // no root CA certificate is attached in the certificate chain, so // getting one from the root CA from JVM. Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode()); if (issuer == null) { throw new RuntimeException("Failed to find the root CA."); } pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i))); } } } return pairIssuerSubject; }
java
private Set<String> getOcspUrls(Certificate bcCert) { TBSCertificate bcTbsCert = bcCert.getTBSCertificate(); Extensions bcExts = bcTbsCert.getExtensions(); if (bcExts == null) { throw new RuntimeException("Failed to get Tbs Certificate."); } Set<String> ocsp = new HashSet<>(); for (Enumeration en = bcExts.oids(); en.hasMoreElements(); ) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement(); Extension bcExt = bcExts.getExtension(oid); if (bcExt.getExtnId() == Extension.authorityInfoAccess) { // OCSP URLS are included in authorityInfoAccess DLSequence seq = (DLSequence) bcExt.getParsedValue(); for (ASN1Encodable asn : seq) { ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray(); if (pairOfAsn.length == 2) { ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0]; if (key == OIDocsp) { // ensure OCSP and not CRL GeneralName gn = GeneralName.getInstance(pairOfAsn[1]); ocsp.add(gn.getName().toString()); } } } } } return ocsp; }
java
private static boolean isValidityRange(Date currentTime, Date thisUpdate, Date nextUpdate) { long tolerableValidity = calculateTolerableVadility(thisUpdate, nextUpdate); return thisUpdate.getTime() - MAX_CLOCK_SKEW_IN_MILLISECONDS <= currentTime.getTime() && currentTime.getTime() <= nextUpdate.getTime() + tolerableValidity; }
java
private void processKeyUpdateDirective(String issuer, String ssd) { try { /** * Get unverified part of the JWT to extract issuer. * */ //PlainJWT jwt_unverified = PlainJWT.parse(ssd); SignedJWT jwt_signed = SignedJWT.parse(ssd); String jwt_issuer = (String) jwt_signed.getHeader().getCustomParam("ssd_iss"); String ssd_pubKey; if (!jwt_issuer.equals(issuer)) { LOGGER.debug("Issuer mismatch. Invalid SSD"); return; } if (jwt_issuer.equals("dep1")) { ssd_pubKey = ssdManager.getPubKey("dep1"); } else { ssd_pubKey = ssdManager.getPubKey("dep2"); } if (ssd_pubKey == null) { LOGGER.debug("Invalid SSD"); return; } String publicKeyContent = ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent)); RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509); /** * Verify signature of the JWT Token */ SignedJWT jwt_token_verified = SignedJWT.parse(ssd); JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey); try { if (jwt_token_verified.verify(jwsVerifier)) { /** * verify nbf time */ long cur_time = System.currentTimeMillis(); Date nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime(); //long nbf = jwt_token_verified.getJWTClaimsSet().getLongClaim("nbf"); //double nbf = jwt_token_verified.getJWTClaimsSet().getDoubleClaim("nbf"); if (cur_time < nbf.getTime()) { LOGGER.debug("The SSD token is not yet valid. Current time less than Not Before Time"); return; } float key_ver = Float.parseFloat(jwt_token_verified.getJWTClaimsSet().getStringClaim("keyVer")); if (key_ver <= ssdManager.getPubKeyVer(jwt_issuer)) { return; } ssdManager.updateKey(jwt_issuer, jwt_token_verified.getJWTClaimsSet().getStringClaim("pubKey"), key_ver); } } catch (Throwable ex) { LOGGER.debug("Failed to verify JWT Token"); throw ex; } } catch (Throwable ex) { LOGGER.debug("Failed to parse JWT Token, aborting"); } }
java
private String ocspResponseToB64(OCSPResp ocspResp) { if (ocspResp == null) { return null; } try { return Base64.encodeBase64String(ocspResp.getEncoded()); } catch (Throwable ex) { LOGGER.debug("Could not convert OCSP Response to Base64"); return null; } }
java
private void scheduleHeartbeat() { // elapsed time in seconds since the last heartbeat long elapsedSecsSinceLastHeartBeat = System.currentTimeMillis() / 1000 - lastHeartbeatStartTimeInSecs; /* * The initial delay for the new scheduling is 0 if the elapsed * time is more than the heartbeat time interval, otherwise it is the * difference between the heartbeat time interval and the elapsed time. */ long initialDelay = Math.max(heartBeatIntervalInSecs - elapsedSecsSinceLastHeartBeat, 0); LOGGER.debug( "schedule heartbeat task with initial delay of {} seconds", initialDelay); // Creates and executes a periodic action to send heartbeats this.heartbeatFuture = this.scheduler.schedule(this, initialDelay, TimeUnit.SECONDS); }
java
public SnowflakeStorageClient createClient(StageInfo stage, int parallel, RemoteStoreFileEncryptionMaterial encMat) throws SnowflakeSQLException { logger.debug("createClient client type={}", stage.getStageType().name()); switch (stage.getStageType()) { case S3: return createS3Client(stage.getCredentials(), parallel, encMat, stage.getRegion()); case AZURE: return createAzureClient(stage, encMat); default: // We don't create a storage client for FS_LOCAL, // so we should only find ourselves here if an unsupported // remote storage client type is specified throw new IllegalArgumentException("Unsupported storage client specified: " + stage.getStageType().name()); } }
java
private SnowflakeS3Client createS3Client(Map stageCredentials, int parallel, RemoteStoreFileEncryptionMaterial encMat, String stageRegion) throws SnowflakeSQLException { final int S3_TRANSFER_MAX_RETRIES = 3; logger.debug("createS3Client encryption={}", (encMat == null ? "no" : "yes")); SnowflakeS3Client s3Client; ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setMaxConnections(parallel + 1); clientConfig.setMaxErrorRetry(S3_TRANSFER_MAX_RETRIES); clientConfig.setDisableSocketProxy(HttpUtil.isSocksProxyDisabled()); logger.debug("s3 client configuration: maxConnection={}, connectionTimeout={}, " + "socketTimeout={}, maxErrorRetry={}", clientConfig.getMaxConnections(), clientConfig.getConnectionTimeout(), clientConfig.getSocketTimeout(), clientConfig.getMaxErrorRetry()); try { s3Client = new SnowflakeS3Client(stageCredentials, clientConfig, encMat, stageRegion); } catch (Exception ex) { logger.debug("Exception creating s3 client", ex); throw ex; } logger.debug("s3 client created"); return s3Client; }
java
public StorageObjectMetadata createStorageMetadataObj(StageInfo.StageType stageType) { switch (stageType) { case S3: return new S3ObjectMetadata(); case AZURE: return new AzureObjectMetadata(); default: // An unsupported remote storage client type was specified // We don't create/implement a storage client for FS_LOCAL, // so we should never end up here while running on local file system throw new IllegalArgumentException("Unsupported stage type specified: " + stageType.name()); } }
java
private SnowflakeAzureClient createAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat) throws SnowflakeSQLException { logger.debug("createAzureClient encryption={}", (encMat == null ? "no" : "yes")); //TODO: implement support for encryption SNOW-33042 SnowflakeAzureClient azureClient; try { azureClient = SnowflakeAzureClient.createSnowflakeAzureClient(stage, encMat); } catch (Exception ex) { logger.debug("Exception creating Azure Storage client", ex); throw ex; } logger.debug("Azure Storage client created"); return azureClient; }
java
public synchronized static BindUploader newInstance(SFSession session, String stageDir) throws BindException { try { Path bindDir = Files.createTempDirectory(PREFIX); return new BindUploader(session, stageDir, bindDir); } catch (IOException ex) { throw new BindException( String.format("Failed to create temporary directory: %s", ex.getMessage()), BindException.Type.OTHER); } }
java