Search in sources :

Example 26 with TrackingKey

use of org.commonjava.indy.folo.model.TrackingKey in project indy by Commonjava.

the class FoloContentAccessResource method doHead.

@ApiOperation("Store and track file/artifact content under the given artifact store (type/name) and path.")
@ApiResponses({ @ApiResponse(code = 404, message = "Content is not available"), @ApiResponse(code = 200, message = "Header metadata for content (or rendered listing when path ends with '/index.html' or '/'") })
@HEAD
@Path("/{path: (.*)}")
public Response doHead(@ApiParam("User-assigned tracking session key") @PathParam("id") final String id, @ApiParam("Package type (eg. maven, npm)") @PathParam("packageType") final String packageType, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @PathParam("name") final String name, @PathParam("path") final String path, @QueryParam(CHECK_CACHE_ONLY) final Boolean cacheOnly, @Context final HttpServletRequest request, @Context final UriInfo uriInfo) {
    final TrackingKey tk = new TrackingKey(id);
    final String baseUri = uriInfo.getBaseUriBuilder().path(BASE_PATH).path(id).build().toString();
    EventMetadata metadata = new EventMetadata().set(TRACKING_KEY, tk).set(ACCESS_CHANNEL, AccessChannel.MAVEN_REPO);
    return handler.doHead(packageType, type, name, path, cacheOnly, baseUri, request, metadata);
}
Also used : TrackingKey(org.commonjava.indy.folo.model.TrackingKey) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) Path(javax.ws.rs.Path) HEAD(javax.ws.rs.HEAD) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 27 with TrackingKey

use of org.commonjava.indy.folo.model.TrackingKey in project indy by Commonjava.

the class FoloContentAccessResource method doGet.

@ApiOperation("Retrieve and track file/artifact content under the given artifact store (type/name) and path.")
@ApiResponses({ @ApiResponse(code = 404, message = "Content is not available"), @ApiResponse(code = 200, response = String.class, message = "Rendered content listing (when path ends with '/index.html' or '/')"), @ApiResponse(code = 200, response = StreamingOutput.class, message = "Content stream") })
@GET
@Path("/{path: (.*)}")
public Response doGet(@ApiParam("User-assigned tracking session key") @PathParam("id") final String id, @ApiParam("Package type (eg. maven, npm)") @PathParam("packageType") final String packageType, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @PathParam("name") final String name, @PathParam("path") final String path, @Context final HttpServletRequest request, @Context final UriInfo uriInfo) {
    final TrackingKey tk = new TrackingKey(id);
    final String baseUri = uriInfo.getBaseUriBuilder().path(BASE_PATH).path(id).build().toString();
    EventMetadata metadata = new EventMetadata().set(TRACKING_KEY, tk).set(ACCESS_CHANNEL, AccessChannel.MAVEN_REPO);
    return handler.doGet(packageType, type, name, path, baseUri, request, metadata);
}
Also used : TrackingKey(org.commonjava.indy.folo.model.TrackingKey) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 28 with TrackingKey

use of org.commonjava.indy.folo.model.TrackingKey in project indy by Commonjava.

the class ProxyResponseWriter method doHandleEvent.

private void doHandleEvent(final ConduitStreamSinkChannel sinkChannel) {
    if (directed) {
        return;
    }
    ProxyMeter meter = new ProxyMeter(httpRequest.getRequestLine().getMethod(), httpRequest.getRequestLine().toString(), startNanos, sliMetricSet, restLogger, peerAddress);
    try {
        HttpConduitWrapper http = new HttpConduitWrapper(sinkChannel, httpRequest, contentController, cacheProvider);
        if (httpRequest == null) {
            if (error != null) {
                logger.debug("Handling error from request reader: " + error.getMessage(), error);
                handleError(error, http);
            } else {
                logger.debug("Invalid state (no error or request) from request reader. Sending 400.");
                try {
                    http.writeStatus(ApplicationStatus.BAD_REQUEST);
                } catch (final IOException e) {
                    logger.error("Failed to write BAD REQUEST for missing HTTP first-line to response channel.", e);
                }
            }
            return;
        }
        restLogger.info("SERVE {} (from: {})", httpRequest.getRequestLine(), peerAddress);
        // TODO: Can we handle this?
        final String oldThreadName = Thread.currentThread().getName();
        Thread.currentThread().setName("PROXY-" + httpRequest.getRequestLine().toString());
        sinkChannel.getCloseSetter().set((c) -> {
            logger.trace("Sink channel closing.");
            Thread.currentThread().setName(oldThreadName);
            if (sslTunnel != null) {
                logger.trace("Close ssl tunnel");
                sslTunnel.close();
            }
        });
        logger.debug("\n\n\n>>>>>>> Handle write\n\n\n");
        if (error == null) {
            ProxyResponseHelper proxyResponseHelper = new ProxyResponseHelper(httpRequest, config, contentController, repoCreator, storeManager, metricsConfig, metricManager, cls);
            try {
                if (repoCreator == null) {
                    throw new IndyDataException("No valid instance of ProxyRepositoryCreator");
                }
                final UserPass proxyUserPass = parse(ApplicationHeader.proxy_authorization, httpRequest, null);
                logger.info("Using proxy authentication: {}", proxyUserPass);
                mdcManager.putExtraHeaders(httpRequest);
                // FIXME: We cannot trace through this interface currently!
                mdcManager.putExternalID(proxyUserPass == null ? null : proxyUserPass.getUser());
                logger.debug("Proxy UserPass: {}\nConfig secured? {}\nConfig tracking type: {}", proxyUserPass, config.isSecured(), config.getTrackingType());
                if (proxyUserPass == null && (config.isSecured() || TrackingType.ALWAYS == config.getTrackingType())) {
                    String realmInfo = String.format(PROXY_AUTHENTICATE_FORMAT, config.getProxyRealm());
                    logger.info("Not authenticated to proxy. Sending response: {} / {}: {}", PROXY_AUTHENTICATION_REQUIRED, proxy_authenticate, realmInfo);
                    http.writeStatus(PROXY_AUTHENTICATION_REQUIRED);
                    http.writeHeader(proxy_authenticate, realmInfo);
                } else {
                    RequestLine requestLine = httpRequest.getRequestLine();
                    String method = requestLine.getMethod().toUpperCase();
                    String trackingId = null;
                    boolean authenticated = true;
                    if (proxyUserPass != null) {
                        TrackingKey trackingKey = proxyResponseHelper.getTrackingKey(proxyUserPass);
                        if (trackingKey != null) {
                            trackingId = trackingKey.getId();
                            RequestContextHelper.setContext(RequestContextHelper.CONTENT_TRACKING_ID, trackingId);
                        }
                        String authCacheKey = generateAuthCacheKey(proxyUserPass);
                        Boolean isAuthToken = proxyAuthCache.get(authCacheKey);
                        if (Boolean.TRUE.equals(isAuthToken)) {
                            authenticated = true;
                            logger.debug("Found auth key in cache");
                        } else {
                            logger.debug("Passing BASIC authentication credentials to Keycloak bearer-token translation authenticator");
                            authenticated = proxyAuthenticator.authenticate(proxyUserPass, http);
                            if (authenticated) {
                                proxyAuthCache.put(authCacheKey, Boolean.TRUE, config.getAuthCacheExpirationHours(), TimeUnit.HOURS);
                            }
                        }
                        logger.debug("Authentication done, result: {}", authenticated);
                    }
                    if (authenticated) {
                        switch(method) {
                            case GET_METHOD:
                            case HEAD_METHOD:
                                {
                                    final URL url = new URL(requestLine.getUri());
                                    logger.debug("getArtifactStore starts, trackingId: {}, url: {}", trackingId, url);
                                    ArtifactStore store = proxyResponseHelper.getArtifactStore(trackingId, url);
                                    proxyResponseHelper.transfer(http, store, url.getPath(), GET_METHOD.equals(method), proxyUserPass, meter);
                                    break;
                                }
                            case OPTIONS_METHOD:
                                {
                                    http.writeStatus(ApplicationStatus.OK);
                                    http.writeHeader(ApplicationHeader.allow, ALLOW_HEADER_VALUE);
                                    break;
                                }
                            case CONNECT_METHOD:
                                {
                                    if (!config.isMITMEnabled()) {
                                        logger.debug("CONNECT method not supported unless MITM-proxying is enabled.");
                                        http.writeStatus(ApplicationStatus.BAD_REQUEST);
                                        break;
                                    }
                                    // e.g, github.com:443
                                    String uri = requestLine.getUri();
                                    logger.debug("Get CONNECT request, uri: {}", uri);
                                    String[] toks = uri.split(":");
                                    String host = toks[0];
                                    int port = parseInt(toks[1]);
                                    directed = true;
                                    // After this, the proxy simply opens a plain socket to the target server and relays
                                    // everything between the initial client and the target server (including the TLS handshake).
                                    SocketChannel socketChannel;
                                    ProxyMITMSSLServer svr = new ProxyMITMSSLServer(host, port, trackingId, proxyUserPass, proxyResponseHelper, contentController, cacheProvider, config, meter);
                                    tunnelAndMITMExecutor.submit(svr);
                                    socketChannel = svr.getSocketChannel();
                                    if (socketChannel == null) {
                                        logger.debug("Failed to get MITM socket channel");
                                        http.writeStatus(ApplicationStatus.SERVER_ERROR);
                                        svr.stop();
                                        break;
                                    }
                                    sslTunnel = new ProxySSLTunnel(sinkChannel, socketChannel, config);
                                    tunnelAndMITMExecutor.submit(sslTunnel);
                                    // client input will be directed to target socket
                                    proxyRequestReader.setProxySSLTunnel(sslTunnel);
                                    // When all is ready, send the 200 to client. Client send the SSL handshake to reader,
                                    // reader direct it to tunnel to MITM. MITM finish the handshake and read the request data,
                                    // retrieve remote content and send back to tunnel to client.
                                    http.writeStatus(ApplicationStatus.OK);
                                    http.writeHeader("Status", "200 OK\n");
                                    break;
                                }
                            default:
                                {
                                    http.writeStatus(ApplicationStatus.METHOD_NOT_ALLOWED);
                                }
                        }
                    }
                }
                logger.debug("Response complete.");
            } catch (final Throwable e) {
                error = e;
            } finally {
                mdcManager.clear();
            }
        }
        if (error != null) {
            handleError(error, http);
        }
        try {
            if (directed) {
                // do not close sink channel
                ;
            } else {
                http.close();
            }
        } catch (final IOException e) {
            logger.error("Failed to shutdown response", e);
        }
    } finally {
        meter.reportResponseSummary();
        span.ifPresent(SpanAdapter::close);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) HttpConduitWrapper(org.commonjava.indy.httprox.util.HttpConduitWrapper) UserPass(org.commonjava.indy.subsys.http.util.UserPass) IOException(java.io.IOException) URL(java.net.URL) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) IndyDataException(org.commonjava.indy.data.IndyDataException) RequestLine(org.apache.http.RequestLine) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) ProxyMeter(org.commonjava.indy.httprox.util.ProxyMeter) ProxyResponseHelper(org.commonjava.indy.httprox.util.ProxyResponseHelper) SpanAdapter(org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter)

Example 29 with TrackingKey

use of org.commonjava.indy.folo.model.TrackingKey in project indy by Commonjava.

the class TrackedContentDTOTest method jsonRoundTrip_DownloadsAndUploads.

@Test
public void jsonRoundTrip_DownloadsAndUploads() throws IOException {
    Set<TrackedContentEntryDTO> downloads = setOf(new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo"), AccessChannel.MAVEN_REPO, "/path/to/my.pom"), new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo2"), AccessChannel.MAVEN_REPO, "/path/to/another/file.pom"));
    Set<TrackedContentEntryDTO> uploads = setOf(new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo3"), AccessChannel.MAVEN_REPO, "/path/to/third/artifact.pom"), new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo3"), AccessChannel.MAVEN_REPO, "/path/to/fourth/project.pom"));
    TrackedContentDTO in = new TrackedContentDTO(new TrackingKey("key"), uploads, downloads);
    assertRoundTrip(in, (out) -> {
        assertContents(out.getUploads(), in.getUploads());
        assertContents(out.getDownloads(), in.getDownloads());
    });
}
Also used : StoreKey(org.commonjava.indy.model.core.StoreKey) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) Test(org.junit.Test)

Example 30 with TrackingKey

use of org.commonjava.indy.folo.model.TrackingKey in project indy by Commonjava.

the class TrackedContentDTOTest method jsonRoundTrip_UploadsNoDownloads.

@Test
public void jsonRoundTrip_UploadsNoDownloads() throws IOException {
    Set<TrackedContentEntryDTO> uploads = setOf(new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo"), AccessChannel.MAVEN_REPO, "/path/to/my.pom"), new TrackedContentEntryDTO(new StoreKey(StoreType.remote, "foo2"), AccessChannel.MAVEN_REPO, "/path/to/another/file.pom"));
    TrackedContentDTO in = new TrackedContentDTO(new TrackingKey("key"), uploads, Collections.emptySet());
    assertRoundTrip(in, (out) -> {
        assertContents(out.getUploads(), in.getUploads());
        assertNullOrEmpty(out.getDownloads());
    });
}
Also used : StoreKey(org.commonjava.indy.model.core.StoreKey) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) Test(org.junit.Test)

Aggregations

TrackingKey (org.commonjava.indy.folo.model.TrackingKey)46 EventMetadata (org.commonjava.maven.galley.event.EventMetadata)18 ApiOperation (io.swagger.annotations.ApiOperation)12 ApiResponses (io.swagger.annotations.ApiResponses)12 Path (javax.ws.rs.Path)12 StoreKey (org.commonjava.indy.model.core.StoreKey)11 Test (org.junit.Test)11 TrackedContent (org.commonjava.indy.folo.model.TrackedContent)10 TrackedContentEntry (org.commonjava.indy.folo.model.TrackedContentEntry)10 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)8 GET (javax.ws.rs.GET)6 HEAD (javax.ws.rs.HEAD)6 PUT (javax.ws.rs.PUT)6 AccessChannel (org.commonjava.indy.model.core.AccessChannel)6 Inject (javax.inject.Inject)4 Context (javax.ws.rs.core.Context)4 KeyedLocation (org.commonjava.indy.model.galley.KeyedLocation)4 Location (org.commonjava.maven.galley.model.Location)4 Transfer (org.commonjava.maven.galley.model.Transfer)4 Logger (org.slf4j.Logger)4